1、 服务端
#include <stdio.h>
#include <winsock2.h>
#include <Windows.h>
#pragma comment(lib , "ws2_32.lib")
DWORD WINAPI ThreadFun(LPVOID lpParam)
{
SOCKET sock = *((SOCKET*)lpParam);
char recvBuf[1000] = "";
char sendBuf[1000] = "";
while (true)
{
int length = recv(sock, recvBuf, 1000, 0);
if (length > 0)
{
printf("客户端:%s\n", recvBuf);
}
else
{
printf("接收失败");
}
printf("请输入你发的信息:");
gets_s(sendBuf);
send(sock, sendBuf, strlen(sendBuf), 0);
}
return 0;
}
int main()
{
printf("服务端\n");
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET servSock = socket(AF_INET,SOCK_STREAM ,IPPROTO_TCP);
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8082);
bind(servSock, (SOCKADDR*)&saddr, sizeof(SOCKADDR));
printf("服务器启动成功!\n等待连接......\n");
while (true)
{
listen(servSock, 15);
int len = sizeof(SOCKADDR);
SOCKADDR_IN caddr;
SOCKET clntSock = accept(servSock, (SOCKADDR*)&caddr, &len);
printf("客户端连接成功!\n");
CreateThread(NULL, 0, ThreadFun, &clntSock, 0, NULL);
printf("子线程创建成功 1!\n");
}
return 0;
}
2、客户端
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib , "ws2_32.lib")
int main()
{
printf("客户端\n");
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8082);
if (connect(sock, (SOCKADDR*)&saddr, sizeof(SOCKADDR)) == 0)
{
printf("客户端连接成功!\n");
while (true)
{
char sendBuf[1000] = "";
char recvBuf[1000] = "";
printf("请输入你发的信息:");
gets_s(sendBuf);
send(sock, sendBuf, strlen(sendBuf) + 1, 0);
Sleep(1000);
recv(sock, recvBuf, 1000, 0);
printf("服务器:%s\n", recvBuf);
}
}
else
{
printf("客户端连接失败!\n");
}
return 0;
}
|