#include <WINSOCK2.H>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
void
main()
{
WORD
myVersionRequest;
WSADATA wsaData;
myVersionRequest=MAKEWORD(1,1);
int
err;
err=WSAStartup(myVersionRequest,&wsaData);
if
(!err)
{
printf
(
"已打开套接字\n"
);
}
else
{
printf
(
"嵌套字未打开!"
);
return
;
}
SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addr;
addr.sin_family=AF_INET;
addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addr.sin_port=htons(6000);
bind(serSocket,(SOCKADDR*)&addr,
sizeof
(SOCKADDR));
listen(serSocket,5);
SOCKADDR_IN clientsocket;
int
len=
sizeof
(SOCKADDR);
while
(1)
{
SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len);
char
sendBuf[100];
sprintf
(sendBuf,
"welcome %s to bejing"
,inet_ntoa(clientsocket.sin_addr));
send(serConn,sendBuf,
strlen
(sendBuf)+1,0);
char
receiveBuf[100];
recv(serConn,receiveBuf,
strlen
(receiveBuf)+1,0);
printf
(
"%s\n"
,receiveBuf);
closesocket(serConn);
WSACleanup();
}
}
client端:
#include <WINSOCK2.H>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
void
main()
{
int
err;
WORD
versionRequired;
WSADATA wsaData;
versionRequired=MAKEWORD(1,1);
err=WSAStartup(versionRequired,&wsaData);
if
(!err)
{
printf
(
"客户端嵌套字已经打开!\n"
);
}
else
{
printf
(
"客户端的嵌套字打开失败!\n"
);
return
;
}
SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN clientsock_in;
clientsock_in.sin_addr.S_un.S_addr=inet_addr(
"127.0.0.1"
);
clientsock_in.sin_family=AF_INET;
clientsock_in.sin_port=htons(6000);
connect(clientSocket,(SOCKADDR*)&clientsock_in,
sizeof
(SOCKADDR));
char
receiveBuf[100];
recv(clientSocket,receiveBuf,101,0);
printf
(
"%s\n"
,receiveBuf);
send(clientSocket,
"hello,this is client"
,
strlen
(
"hello,this is client"
)+1,0);
closesocket(clientSocket);
WSACleanup();
}