服务端代码:
#include<stdio.h>
#include<winsock2.h>//套接字相关函数的头文件
#pragma comment(lib,"ws2_32.lib")//链接库文件
void main()
{
char SendBuf[100],ReceiveBuf[100];
int Length;
SOCKET socket_server,socket_receive;
SOCKADDR_IN Server_add,Client_add;
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2),&wsaData);
Server_add.sin_family=AF_INET;//地址家族,必须为AF_INET
Server_add.sin_addr.S_un.S_addr=inet_addr("119.39.0.67");//IP地址,具体取决于你自己电脑上的地址
Server_add.sin_port=htons(5000);
socket_server=socket(AF_INET,SOCK_STREAM,0);
bind(socket_server,(SOCKADDR *)&Server_add,sizeof(SOCKADDR));
listen(socket_server,2);
Length=sizeof(SOCKADDR);
//下面这个语句,会一直等待,直到有客户端发送连接请求connect,这是阻塞模式
socket_receive=accept(socket_server,(SOCKADDR *)&Client_add,&Length);
printf("已有客户连接...\n");
while(1)
{
recv(socket_receive,ReceiveBuf,100,0);//阻塞模式,直有到数据发过来,才执行后面的语句
printf("%s\n",ReceiveBuf);
printf("Please enter message:");
scanf("%s",SendBuf);
send(socket_receive,SendBuf,100,0);//发送数据
}
}
客户端代码:
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
char SendBuf[100],ReceiveBuf[100];
SOCKET sock_receive;
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2),&wsaData);
SOCKADDR_IN Server_add;
Server_add.sin_family=AF_INET;//地址家族,必须为AF_INET
Server_add.sin_addr.S_un.S_addr=inet_addr("119.39.0.67");//IP地址,具体取决于你自己电脑上的地址
Server_add.sin_port=htons(5000);
sock_receive=socket(AF_INET,SOCK_STREAM,0);
connect(sock_receive,(SOCKADDR *)&Server_add,sizeof(SOCKADDR));
while(1)
{
printf("Please enter message:");
scanf("%s",SendBuf);
send(sock_receive,SendBuf,100,0);
recv(sock_receive,ReceiveBuf,100,0);
printf("%s\n",ReceiveBuf);
}
}
上面这个简易的聊天程序,只能按顺序聊天,也就是客户端先发送数据,发送过去之后,要想再发送数据,就必须等服务端发送数据过来。有点像呼叫机。
(转)UDP协议下的例子,客户端发送字符串给服务端,服务端将其转化成大写,再发回去。客户端接收并输出
服务端代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")#define BUFSIZE 256
void main(void)
{ struct sockaddr_in client,server;
SOCKET s;
in tlen,i,n;
char buf[BUFSIZE];
//初始化winsock
WSADATA wsaData;
WSAStartup(0x0202,&wsaData);
//建立套接字
s=socket(AF_INET,SOCK_DGRAM,0);
//初始化服务器地址结构
memset((char*)&server,0,sizeof(server));
server.sin_family =AF_INET;
server.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
server.sin_port =htons(5320);
//绑定socket对象到服务器地址
bind(s,(struct sockaddr*)&server,sizeof(server));
//不需要初始化客户端地址结构
//接收客户端发送来的字符串,回送客户端
len=sizeof(client);
while((n=recvfrom(s,buf,BUFSIZE,0,(struct sockaddr*)&client,&len))>0)
{
for(i=0;i<n;i++)
buf[i]=toupper(buf[i]);
sendto(s,buf,n,0,(struct sockaddr*)&client,len);
}
//关闭socket
closesocket(s);
WSACleanup();
exit(0);
}
客户端代码: