TCP聊天的一些基础设置咨询
上两个帖子还是没有起到关键的作用,所以关于TCP聊天系统的一些基本文件和代码上的问题我想在向大佬请教一下。代码是按网上教程和版主的指导写的。但是我的电脑是2018年产的,不知道有没有少文件,所以发这一帖。程序代码:
//客户端 #include<stdio.h> #include<windows.h> #include<winsock.h> #pragma comment(lib,"ws2_32.lib") int main(void) { WSADATA wsadata = { 0 }; WSAStartup(MAKEWORD(2, 2), &wsadata); if (wsadata.wVersion != MAKEWORD(2, 2)) { puts("请求协议版本失败"); return 1; } puts("请求协议成功"); SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == clientSocket) { puts("创建套接字失败"); WSACleanup(); return 2; } puts("创建套接字成功"); SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.1"); // inet_addr("192.168.1.1"); addr.sin_port = htons(10087); //addr.sin_port = htons(10087); int r = connect(clientSocket, (SOCKADDR*)&addr, sizeof addr); if (r == SOCKET_ERROR) { puts("链接服务器失败"); return 0; } puts("连接服务器成功"); while (1) { printf("你想说啥\n"); char buff[1024]; getchar("%s", &buff); send(clientSocket, buff, strlen(buff), NULL); } closesocket(clientSocket); WSACleanup(); return 0; }
程序代码:
//服务器端 #include<stdio.h> #include<windows.h> #include<winsock.h> #pragma comment(lib,"ws2_32.lib") int main(void) { WSADATA wsadata = { 0 }; WSAStartup(MAKEWORD(2, 2), &wsadata); if (wsadata.wVersion != MAKEWORD(2, 2)) { puts("请求协议版本失败"); return 1; } puts("请求协议成功"); SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (INVALID_SOCKET == serverSocket) { puts("创建套接字失败"); WSACleanup(); return 2; } puts("创建套接字成功"); SOCKADDR_IN addr = { 0 }; addr.sin_family = AF_INET; addr.sin_addr.S_un.S_addr = inet_addr("192.168.1.1"); // inet_addr("192.168.1.1"); addr.sin_port = htons(10086); int r = bind(serverSocket, (SOCKADDR*)&addr, sizeof addr); if (SOCKET_ERROR == r) { puts("bind失败"); closesocket(serverSocket); WSACleanup(); return 3; } printf("bind成功"); r = listen(serverSocket, 10); if (SOCKET_ERROR == r) { puts("监听失败"); closesocket(serverSocket); WSACleanup(); return 4; } printf("监听成功\n"); for (; ; ) { SOCKADDR_IN cAddr = { 0 }; int len = sizeof cAddr; SOCKET clientSocket = accept(serverSocket, (SOCKADDR*)&cAddr, &len); if (INVALID_SOCKET == clientSocket) { puts("服务器宕机了"); closesocket(serverSocket); WSACleanup(); return 5; } printf("有客户端连接到服务器了:%s\n", inet_ntoa(cAddr.sin_addr)); for (char buff[1024]; ; ) { r = recv(clientSocket, buff, 1024, NULL); if (r > 0) { printf(">>%.*s\n", r, buff); } } } closesocket(serverSocket); WSACleanup(); //return 0; }