在socket文件夹下创建server.c和client.c。
服务端代码(server.c):
#include <stdio.h>
#include <Winsock2.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 sockSrv=socket(AF_INET,SOCK_STREAM,0);SOCKADDR_IN addrSrv;addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);addrSrv.sin_family=AF_INET;addrSrv.sin_port=htons(6000);bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));listen(sockSrv,5);SOCKADDR_IN addrClient;int len=sizeof(SOCKADDR);while(1){SOCKET sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);char sendBuf[50];sprintf(sendBuf,"Welcome %s to here!",inet_ntoa(addrClient.sin_addr));send(sockConn,sendBuf,strlen(sendBuf)+1,0);char recvBuf[50];recv(sockConn,recvBuf,50,0);printf("%s\n",recvBuf);closesocket(sockConn);}
}
客户端代码(client.c):
#include <stdio.h>
#include <Winsock2.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_STREAM,0);SOCKADDR_IN addrSrv;addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");addrSrv.sin_family=AF_INET;addrSrv.sin_port=htons(6000);connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));send(sockClient,"hello",strlen("hello")+1,0);char recvBuf[50];recv(sockClient,recvBuf,50,0);printf("%s\n",recvBuf);closesocket(sockClient);WSACleanup();
}
在socket文件夹目录下打开两个cmd窗口,先各自编译server.c和client.c,并在socket目录下生成server.exe和client.exe。
gcc -o client client.c -lws2_32
gcc -o server server.c -lws2_32
编译完后运行server.exe和client.exe,在运行完client.exe后可以在server界面中中看到hello,并且在client界面中看到welcome 127.0.0.1 to here!
若要结束server.exe,在server界面中按下ctrl+C。
python版本的socket通信:
服务端(server.py):
import socket# 初始化服务器套接字
sock_srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置服务器地址和端口
addr_srv = ('', 6000)# 将服务器套接字绑定到指定地址和端口
sock_srv.bind(addr_srv)# 开始监听连接请求
sock_srv.listen(5)while True:# 接受客户端连接并处理通信sock_conn, addr_client = sock_srv.accept()# 发送欢迎消息给客户端send_buf = f"Welcome {addr_client[0]} to here!"sock_conn.send(send_buf.encode())# 接收客户端发送的消息并打印recv_buf = sock_conn.recv(1024).decode()print(recv_buf)# 关闭与客户端的连接sock_conn.close()# 关闭服务器套接字
sock_srv.close()
客户端(client.py):
import socket# 初始化客户端套接字
sock_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 设置服务器地址和端口
addr_srv = ('127.0.0.1', 6000)# 连接到服务器
sock_client.connect(addr_srv)# 发送消息给服务器
sock_client.send("hello".encode())# 接收服务器发送的消息并打印
recv_buf = sock_client.recv(1024).decode()
print(recv_buf)# 关闭客户端套接字
sock_client.close()
进入server.py和client.py所在的socket文件夹的两个cmd,分别为server端和client端,分别运行:
python server.py
python client.py
运行client.py后可以在先运行的server界面看到hello,并且在client界面看到welcome 127.0.0.1 to here!