简单的socket通信TCP

Tcp Server:

View Code
#include <stdio.h>
#include
<Winsock2.h>
#pragma comment(lib,"ws2_32.lib")

void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested
= MAKEWORD(2,2);
err
= WSAStartup(wVersionRequested,&wsaData);
if (err!=0)
{
return;
}
if ((LOBYTE(wsaData.wVersion)!=2)||(HIBYTE(wsaData.wVersion)!=2))
{
WSACleanup();
return;
}
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr
=htonl(INADDR_ANY);
addrSrv.sin_family
=AF_INET;
addrSrv.sin_port
=htons(6000);

int len = sizeof(SOCKADDR);

SOCKET socketSrv
=socket(AF_INET,SOCK_STREAM,0);
bind(socketSrv,(SOCKADDR
*)&addrSrv,len);
listen(socketSrv,
5);
SOCKADDR_IN addrConn;

while(1) {
SOCKET socketConn
=accept(socketSrv,(SOCKADDR*)&addrConn,&len);
char sendBuf[100];
sprintf(sendBuf,
"Welcome %s to TCP Server.",inet_ntoa(addrConn.sin_addr));
send(socketConn,sendBuf,strlen(sendBuf)
+1,0);
char recvBuf[100];
recv(socketConn,recvBuf,
100,0);
printf(
"%s\n",recvBuf);
closesocket(socketConn);
}

closesocket(socketSrv);
WSACleanup();

return;
}

Tcp Client:

View Code
#include <stdio.h>
#include
<Winsock2.h>
#pragma comment(lib,"ws2_32.lib")

void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested
=MAKEWORD(2,2);
err
=WSAStartup(wVersionRequested,&wsaData);
if (err!=0)
{
return;
}
if ((LOBYTE(wsaData.wVersion)!=2)||(HIBYTE(wsaData.wVersion)!=2))
{
WSACleanup();
return;
}
SOCKADDR_IN addrClient;
addrClient.sin_addr.S_un.S_addr
=inet_addr("127.0.0.1");
addrClient.sin_family
=AF_INET;
addrClient.sin_port
=htons(6000);
int len=sizeof(SOCKADDR);

SOCKET socketClient
=socket(AF_INET,SOCK_STREAM,0);

connect(socketClient,(SOCKADDR
*)&addrClient,len);

char recvBuf[100];
recv(socketClient,recvBuf,
100,0);
printf(
"%s\n",recvBuf);

char *sendBuf="This is Tcp Client.";
send(socketClient,sendBuf,strlen(sendBuf)
+1,0);

closesocket(socketClient);

WSACleanup();

return;
}
posted @ 2011-03-13 10:32  Jekhn  阅读(278)  评论(0编辑  收藏  举报