资源简介
C语言套接字编程TCP连接,实现功能.先启动服务器端,然后,启动客户端。服务器IP地址要改。
代码片段和文件信息
#include
#include
#pragma comment(lib“ws2_32.lib“)
#include
#include
//#include
#include
int main()
{
WSADATA wsaData;
SOCKET ClientSocket;
SOCKADDR_IN ServerAddr;
int ServerPort=4000;
char ServerIPAddr[50]=“10.106.47.106“;//是否要改
char*SendData=“Hello World!“;
char ReceiveBuffer[1024]=““;
int SendLength=-1;
int Result=-1;
if((Result=WSAStartup(MAKEWORD(22)&wsaData))!=0)
{
printf(“WSAStartup failed with error%d\n“Result);
return 0;
}
ClientSocket=socket(AF_INET
SOCK_STREAM
IPPROTO_TCP);
if(ClientSocket<0)
{
printf(“socket failed with error%d\n“WSAGetLastError());
return 0;
}
memset(&ServerAddr0sizeof(ServerAddr));
ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(ServerPort);
ServerAddr.sin_addr.s_addr=inet_addr(ServerIPAddr);
Result=connect(ClientSocket
(SOCKADDR*)&ServerAddr
sizeof(ServerAddr));
if(Result<0)
{
printf(“connect failed with error%d\n“WSAGetLastError());
return 0;
}
SendLength=send(ClientSocket
SendData
strlen(SendData)
0);
if(SendLength<0)
{
printf(“send failed with error%d\n“WSAGetLastError());
return 0;
}
else
{
printf(“Send Data:%s\n“SendData);
}
int ReceiveLen;
memset(ReceiveBuffer0sizeof(ReceiveBuffer));
if((ReceiveLen=recv(ClientSocket
ReceiveBuffer
1024
0))<0)
{
printf(“recv failed with error %d\n“WSAGetLastError());
return 0;
}
else
{
printf(“Receive Data:%s\n“ReceiveBuffer);
}
if(closesocket(ClientSocket)==SOCKET_ERROR)
{
printf(“closesocket failed with error%d\n“WSAGetLastError());
}
if(WSACleanup()==SOCKET_ERROR)
{
printf(“WSACleanup failed with error%d\n“WSAGetLastError());
}
system(“PAUSE“);
return EXIT_SUCCESS;
}
属性 大小 日期 时间 名称
----------- --------- ---------- ----- ----
文件 2360 2011-09-27 23:42 TCP服务器001.cpp
文件 1759 2011-12-18 15:10 TCP客户端001.cpp
文件 42 2011-12-18 15:10 说明.txt
----------- --------- ---------- ----- ----
4161 3
- 上一篇:自动调整界面布局的对话框
- 下一篇:sanke.cpp
评论
共有 条评论