下面是个socket编程的例子——客户端可发送字符到服务端,服务端负责显示客户端发送过来的字符。
客户端:
#include
#include
#pragma comment(lib,"WS2_32.LIB")
#define Port 3578
#define MaxSize 1024
void main()
{
WORD
wVersionRequested;
WSADATA
wsaData;
int err;
wVersionRequested=MAKEWORD(2,2);
err=WSAStartup(wVersionRequested,&wsaData);
if
(err!=0)
{
printf("WinSock DLL版本不足要求n");
return;
}
if
(LOBYTE(wsaData.wVersion)!=2||
HIBYTE(wsaData.wVersion)!=2)
{
WSACleanup();
return;
}
//创建套接字
SOCKET
sockClient=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//把U_LONG的主机字节顺序转换为TCP/IP网络字节顺序
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(Port);
//向服务器发送请求
if(connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR))
== -1)
{
printf("连接失败!输入回车结束程序!n");
getchar();
return;
}
//接受数据
char
recBuf[MaxSize];
recv(sockClient,recBuf,MaxSize,0);
printf("%sn",recBuf);
//输入name
printf("Input your Name:n");
char
name[20] = {0};
gets(name);
//发送数据
send(sockClient,name,strlen(name)+1,0);
while(1)
{
gets(recBuf);
send(sockClient,recBuf,strlen(recBuf)+1,0);
}
//关闭套接字
closesocket(sockClient);
getchar();
WSACleanup();
}
服务器端:
#include
#include
#pragma comment(lib,"WS2_32.LIB")
#define Port 3578
#define MaxSize 1024
void main()
{
//加载套接字
WORD
wVersionRequested;
WSADATA
wsaData;
int err;
wVersionRequested=MAKEWORD(2,2);
err =
WSAStartup(wVersionRequested,&wsaData);
if
(err!=0)
{
printf("WinSock DLL版本不足要求n");
return;
}
if
(LOBYTE(wsaData.wVersion)!=2||
HIBYTE(wsaData.wVersion)!=2)
{
WSACleanup();
return;
}
//创建监听的套接字
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN addrSrv;
//把U_LONG的主机字节顺序转换为TCP/IP网络字节顺序
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY)
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(Port);
//绑定套接字
bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
//将套接字设置为监听模式,准备接受用户请求
listen(sockSrv,5);
SOCKADDR_IN
addrClient;
int len=sizeof(SOCKADDR);
printf("%sn","Welcome,the Host is running!nWating for someone comes
in!");
while (1)
{
//等待用户请求到来
SOCKET
sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
char
sendBuf[MaxSize];
sprintf(sendBuf,"Welcome to the Host,%s.",
inet_ntoa(addrClient.sin_addr));
//发送数据
send(sockConn,sendBuf,MaxSize,0);
//接收数据
char
revBuf[MaxSize];
char name[20] = {0};
int flag = 1;
while(recv(sockConn,revBuf,MaxSize,0) != -1)
{
//打印接受数据
if(flag == 1)
{
strcpy(name, revBuf);
printf("%s comes in!n",name);
flag = 2;
}