- 论坛徽章:
- 0
|
- # include <stdio.h>
- # ifndef WIN32
- # include <sys/socket.h>
- # include <unistd.h>
- # include <netinet/in.h>
- # include <arpa/inet.h>
- # include <pthread.h>
- # define closesocket(a) close(a)
- # else
- # include <winsock2.h>
- # endif
- # define MAXBUF 512
- # define PORT 2222
- void rcv(); /*后台接收消息的函数 */
- void snd(); /*发送消息的函数*/
- /*简介:该程序是一个跨平台的一个简单的基于UDP协议聊天工具
- 功能:主线程:发送消息
- 子线程:接收消息
- 作者:wjfree
- 使用:运行后发送消息:IP +空格+ Message
- 编译:linux 下:gcc ./chatlin.c -lpthread -o chat
- win下:在lcc下添加工程,编译
- */
- int main ()
- {
- # ifdef WIN32
- WSADATA wsaData;
- WORD wVersionRequested = MAKEWORD( 2, 2 );
- int err = WSAStartup( wVersionRequested, &wsaData );
- HANDLE hThread;
- DWORD dwThreadId;
- hThread = CreateThread(NULL,0,rcv,NULL,0,&dwThreadId);
- snd();
- WSACleanup();
- # else
- pthread_t id;
- int ret;
- ret = pthread_create(&id,NULL,(void *)rcv,NULL); /*创建一个线程*/
- snd();
- # endif
- return 0;
- }
- /*函数:snd()
- 功能:用scanf()函数接收ip地址和消息内容,发到对应的IP上
- 作者:wjfree
- */
- void snd()
- {
- struct sockaddr_in name;
- int sock;
- name.sin_family = PF_INET;
- name.sin_port = htons(PORT);
- sock = socket(PF_INET, SOCK_DGRAM,0);
- if (sock < 0)
- {
- printf("make socket error\n");
- return;
- }
- while(1)
- {
- char bufloc[MAXBUF];
- char ipaddr[17];
- scanf("%s%s" , ipaddr, bufloc);
- int i = name.sin_addr.s_addr = inet_addr(ipaddr);
- if (i == -1)
- {
- printf("IP address format error!\n");
- }
- else
- {
- int i = sendto(sock, bufloc, strlen(bufloc), 0, (struct sockaddr *)&name, sizeof(name));
- if (i < 0)
- printf("Can not send the message to %s\n", ipaddr);
- }
- }
- closesocket(sock);
- }
- /*函数:snd()
- 功能:接收消息并显示在终端
- 作者:wjfree
- */
- void rcv()
- {
- struct sockaddr_in RecvAddr;
- struct sockaddr_in SenderAddr;
- int sock;
- sock = socket(AF_INET, SOCK_DGRAM, 0);
- RecvAddr.sin_family = AF_INET;
- RecvAddr.sin_port = htons(PORT);
- RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- bind(sock, (struct sockaddr *) &RecvAddr, sizeof(RecvAddr));
- printf("Receiving datagrams...\n");
- while(1)
- {
- int size = sizeof(SenderAddr);
- char RecvBuf[MAXBUF];
- int BufLen = MAXBUF;
- int i = recvfrom(sock,
- RecvBuf,
- BufLen,
- 0,
- (struct sockaddr *)&SenderAddr,
- &size);
- RecvBuf[i] = 0;
- printf("%s: %s\n", inet_ntoa(SenderAddr.sin_addr),RecvBuf);
- }
- closesocket(sock);
- }
复制代码
这是代码,一个小聊天程序在linux+gcc和win+lcc可以编译,但是将# ifndef WIN32改成# ifdef LINUX 就不行了 |
|