Socket.rar

  • t3_754443
    了解作者
  • 1.9KB
    文件大小
  • rar
    文件格式
  • 0
    收藏次数
  • VIP专享
    资源类型
  • 0
    下载次数
  • 2022-06-15 10:25
    上传日期
Winsock网络通信,由C编写,可实现单服务器多客户端通信(改进一下可以实现客户端间通信) 如果要外网通信,请更改路由器配置以及客户端IP通信地址
Socket.rar
  • server.c
    1.9KB
  • client.c
    1.1KB
内容介绍
//#include <WinSock2.h> #include <Windows.h> #include <stdio.h> #include <process.h> #pragma warning(disable:4996) #pragma comment(lib,"ws2_32.lib") #define PORT 500 //端口号 SOCKET clientSocket[1024] = { 0 }; DWORD proc(LPVOID lpThreadParameter) { int m = (int)lpThreadParameter; char buf[256]; int r; while (1) { memset(buf, 0, 256); r = recv(clientSocket[m], buf, 255, 0); if (r > 0) { printf("Client[%d]:%s",m ,buf); //buf中含有\n } else if (r == SOCKET_ERROR) { clientSocket[m] = 0; switch (WSAGetLastError()) { case 0x2746: printf("Socket[%d] 连接关闭\n", m); break; } return 0; } } } //判断空余Socket索引 int GetLatestSocket() { int i = 0; while (i <= 1024 && clientSocket[i++]); if (--i == 1024) return -1; else return i; } int main(int argc, char* argv[]) { //请求版本号 WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { return -1; } if (HIBYTE(wsaData.wVersion) != 2 || LOBYTE(wsaData.wVersion) != 2) { printf("请求版本失败!"); return -1; } //创建socket SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //创建协议地址族 SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = INADDR_ANY; addr.sin_port = htons(PORT); //绑定 int r = bind(serverSocket, (SOCKADDR*)&addr, sizeof addr); //监听 r = listen(serverSocket, 10); //接受客户端连接 创建传输通道 SOCKADDR_IN cAddr = { 0 }; int size = sizeof cAddr; //接收用户进入信息 int index = 0; while ((index = GetLatestSocket())+1) { clientSocket[index] = accept(serverSocket, (SOCKADDR*)&cAddr, &size); if (clientSocket[index] == INVALID_SOCKET) break; printf("A New Member Came In.\n"); if (!_beginthread(proc, 0, (void*)index)) { puts("Failed To Create Thread"); } } //断开连接 closesocket(clientSocket[index]); //清除协议信息 WSACleanup(); return 0; }
评论