引自:http://hi.baidu.com/tjulxh/blog/item/74d9f4dc9e5442335882dd70.html
服务器端程序:
1. 创建套接字(socket);
2. 将套接字绑定到一个本地地址和端口上(bind);
3. 将套接字设为监听模式,准备接收客户端请求(listen);
4. 等待客户端请求,当请求到达后,接受连接请求,返回一个新的对应于此次连接的套接字(accept);
5. 用返回的套接字和客户端进行通信(send/recv);
6. 返回,等待另一客户请求;
7. 关闭套接字;
客户端程序:
1. 创建套接字(socket);
2. 向服务器端发出连接请求(connect);
3. 和服务器端进行通信(send/recv);
4. 关闭套接字;
--------------------------------------------------
基于 UDP (面向无连接)的 socket 编程
服务器端(接收端)程序:
1. 创建套接字(socket);
2. 将套接字绑定到一个本地地址和端口上(bind);
3. 等待接收数据(recvfrom);
4. 关闭套接字;
客户端(发送端)程序:
1. 创建套接字(socket);
2. 向服务器端发送数据(sendto);
3. 关闭套接字;
/// UDP dos环境 聊天程序服务器端 (Server)
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return; // 加载套接字库失败,则返回
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup();
return;
}
SOCKET sockServer = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
bind(sockServer,(SOCKADDR *)&addrServer,sizeof(SOCKADDR));
SOCKADDR_IN addrClient;
int len = sizeof(SOCKADDR);
char recvBuff[256];
char sendBuff[256];
char tempBuff[256];
while(1)
{
recvfrom(sockServer,recvBuff,256,0,(SOCKADDR *)&addrClient,&len);
if(recvBuff[0] == 'q')
{
sendto(sockServer,"q",strlen("q")+1,0,(SOCKADDR *)&addrClient,sizeof(SOCKADDR));
printf("Chat End !/n");
break;
}
sprintf(tempBuff,"%s says : %s",inet_ntoa(addrClient.sin_addr),recvBuff);
printf("%s/n",tempBuff); // 将接收到的数据打印输出
printf("Please input data: ");
gets(sendBuff);
sendto(sockServer,sendBuff,strlen(sendBuff)+1,0,(SOCKADDR *)&addrClient,sizeof(SOCKADDR));
}
closesocket(sockServer);
WSACleanup();
}
/客户端(Client):
#include <Winsock2.h>
#include <stdio.h>
void main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return;
}
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup();
return;
}
SOCKET sockClient = socket(AF_INET,SOCK_DGRAM,0);
SOCKADDR_IN addrServer;
addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addrServer.sin_family = AF_INET;
addrServer.sin_port = htons(6000);
int len = sizeof(SOCKADDR);
char sendBuff[256];
char recvBuff[256];
char tempBuff[256];
while(1)
{
printf("Please input data: ");
gets(sendBuff);
sendto(sockClient,sendBuff,strlen(sendBuff)+1,0,(SOCKADDR *)&addrServer,sizeof(SOCKADDR));
recvfrom(sockClient,recvBuff,256,0,(SOCKADDR *)&addrServer,&len);
if(recvBuff[0] == 'q')
{
sendto(sockClient,"q",strlen("q")+1,0,(SOCKADDR *)&addrServer,sizeof(SOCKADDR));
printf("Chat End !/n");
break;
}
sprintf(tempBuff,"%s Says : %s",inet_ntoa(addrServer.sin_addr),recvBuff);
printf("%s/n",tempBuff);
}
closesocket(sockClient);
WSACleanup();
}