MingGW 内外中编写程序进行udp 通信
2015-07-24 11:36
316 查看
首先用python 编写一个server
而又用c编写一个client
用下面的编译
gcc winclient.c -lws2_32
而后就可以运行了。
import socket address = ('127.0.0.1', 21567) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(address) while True: data, addr = s.recvfrom(2048) if not data: print "client has exist" break print "received:", data, "from", addr s.close()
而又用c编写一个client
#include<stdio.h> #include<winsock2.h> #pragma comment(lib,"ws2_32.lib") //Winsock Library #define SERVER "127.0.0.1" //ip address of udp server #define BUFLEN 512 //Max length of buffer #define PORT 21567 //The port on which to listen for incoming data int main(void) { struct sockaddr_in si_other; int s, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; WSADATA wsa; //Initialise winsock printf("\nInitialising Winsock..."); if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) { printf("Failed. Error Code : %d",WSAGetLastError()); exit(EXIT_FAILURE); } printf("Initialised.\n"); //create socket if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) { printf("socket() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } //setup address structure memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); si_other.sin_addr.S_un.S_addr = inet_addr(SERVER); //start communication while(1) { printf("Enter message : "); gets(message); //send the message if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR) { printf("sendto() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } //receive a reply and print it //clear the buffer by filling null, it might have previously received data memset(buf,'\0', BUFLEN); //try to receive some data, this is a blocking call if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR) { printf("recvfrom() failed with error code : %d" , WSAGetLastError()); exit(EXIT_FAILURE); } puts(buf); } closesocket(s); WSACleanup(); return 0; }
用下面的编译
gcc winclient.c -lws2_32
而后就可以运行了。
相关文章推荐
- php字符串
- Rational Rose类图:显示函数签名
- The JRE could not be found. Edit the server and change the JRE location.
- 计算机基础之透析我家的组装机
- Android系统JNI的实现方式
- ORACLE 进程
- CentOS6, CentOS7 线上服务器更新 ssh 安全配置
- dedecms 调用全部导航+二级导航
- iOS求职之OC面试题
- 字典
- [Java Web]EasyUI中Calendar预设时间的解决
- libevent的ssl加密功能
- openssl编程之服务端
- tomcat 配置下载链接
- POJ 3087:Shuffle'm Up
- android 显示基础原理
- JAVA流操作(3)对象流
- 微信企业号 - OAuth验证接口
- POJ 3087:Shuffle'm Up
- 多维数组a[x][y]的指针操作及ptr+1 a+1和&a+1区别