初学socket,c语言写的简单局域网聊天
在客户端所在的目录新建一个IP.bwj的文件,写上服务端的IP,不要带空格,保存。双方都打开一个客户端和一个服务端就可以聊天了,(可以写自己的IP,自己跟自己聊。。)没有第三方服务器,服务端所在的电脑就是服务器。程序通过AF_INET协议族,监听7464端口,没写任何错误处理,这样便于突出主要矛盾嘛。。初学见笑。。
不知道死循环应该怎么退出,客户端可以通过输入的buffer写一个退出命令,不知道服务端怎么办,调用kbhit也不行,因为recvfrom一直在监听,我再想想。。
客户端
#include<stdio.h> #include<winsock.h> #pragma comment (lib,"wsock32.lib") int main() { char IPAdd[30]; FILE *readIP = fopen("IP.bwj", "r"); fscanf(readIP, "%s", IPAdd); fclose(readIP); char buffer[1024]; WSADATA data; WSAStartup(MAKEWORD(2,0), &data); SOCKET mySocket; struct sockaddr_in server; int len = sizeof(server); server.sin_family = AF_INET; server.sin_port = htons(7464); server.sin_addr.s_addr = inet_addr(IPAdd); mySocket = socket(AF_INET, SOCK_DGRAM, 0); while(1) { scanf("%s", buffer); if(strcmp(buffer, "exit") == 0)break; sendto(mySocket, buffer, sizeof(buffer), 0,(struct sockaddr*)&server, len); } closesocket(mySocket); WSACleanup(); return 0; }
服务端
#include <stdio.h> #include <winsock.h> #pragma comment (lib, "wsock32.lib") int main() { char buffer[1024]; WSADATA data; WSAStartup(MAKEWORD(2,0), &data); SOCKET mySocket; struct sockaddr_in local; struct sockaddr_in from; local.sin_family = AF_INET; local.sin_port = htons(7464); local.sin_addr.s_addr = INADDR_ANY; mySocket = socket(AF_INET, SOCK_DGRAM, 0); bind(mySocket, (struct sockaddr*)&local, sizeof(local)); int len = sizeof(from); while(1) { recvfrom(mySocket, buffer, sizeof(buffer), 0, (struct sockaddr*)&from, &len); printf("Received from %s :\n%s\n", inet_ntoa(from.sin_addr), buffer); } closesocket(mySocket); WSACleanup(); return 0; }