提供的代码不能通过编译,好象缺少文件?
简单写了个示例参考,暂时不考虑线程同步的问题。
修改一下应该可以扩展到监听多个端口,无需写多个S端。
/* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
// winsock2.h 要放到 windows.h 的上面
#include <windows.h>
//#pragma comment(lib,"ws2_32.lib")
#define BUFFER_SIZE
256
DWORD WINAPI ThreadProc(SOCKET hSockClient)
{
char buf[BUFFER_SIZE];
int ret;
while (1)
{
ret = recv(hSockClient, buf, BUFFER_SIZE, 0);
if (ret > 0)
{
if (strcmp(buf, "bye") == 0)
break;
printf("%s\n", buf);
send(hSockClient, buf, strlen(buf)+1, 0);
}
Sleep(1000);
}
closesocket(hSockClient);
return 0;
}
int main(void)
{
WSADATA wsadata;
if (WSAStartup(MAKEWORD(2,2),&wsadata) != 0)
{
printf("WSA初始化失败\n");
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
sin.sin_port = htons(8888);
SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bind(hSocket, (LPSOCKADDR)&sin, sizeof(sin));
listen(hSocket, 5);
SOCKADDR_IN sinClient;
int len = sizeof(sinClient);
SOCKET hSockClient;
HANDLE hThread;
while (1)
{
hSockClient = accept(hSocket, (LPSOCKADDR)&sinClient, &len);
if(hSockClient == INVALID_SOCKET)
{
printf("Accept Failed!\n");
continue;
}
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, (LPVOID)hSockClient, 0, 0);
if (hThread != NULL)
CloseHandle(hThread);
Sleep(1000);
}
closesocket(hSocket);
WSACleanup();
system("pause");
return 0;
}
/* client.c */
#include <stdio.h>
#include <string.h>
#include <winsock2.h>
// winsock2.h 要放到 windows.h 的上面
#include <windows.h>
//#pragma comment(lib,"ws2_32.lib")
#define BUFFER_SIZE
256
int main(void)
{
WSADATA wsadata;
if(WSAStartup(MAKEWORD(2,2),&wsadata) != 0)
{
printf("WSA初始化失败\n");
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8888);
sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
{
printf("socket创建失败\n");
WSACleanup();
return -1;
}
if (connect(hSocket,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR)
{
printf("socket客户端连接失败\n");
closesocket(hSocket);
WSACleanup();
return -1;
}
char buf[BUFFER_SIZE];
int ret;
while (1)
{
printf("我:");
scanf("%s", buf);
ret = send(hSocket, buf, strlen(buf)+1, 0);
if (strcmp(buf,"bye") == 0)
break;
ret = recv(hSocket, buf, BUFFER_SIZE, 0);
if (ret > 0)
printf("服务器:%s\n", buf);
}
closesocket(hSocket);
WSACleanup();
system("pause");
return 0;
}