网络编程(socket 发送 & 接收信息)
2013-10-20 18:00
162 查看
在命令提示符系 通过 C/S 方式发送与接收信息
首先是 TCP 面向连接的方式:
这是服务器端:
这是客户端:
运行时,必须先启动服务器端,然后才能显示
然后是 UDP面向无连接的方式 运行上面的,但是 这次可以 服务器端和客户端会话:
首先是服务器端代码:
然后是客户端代码:
首先是 TCP 面向连接的方式:
这是服务器端:
#include <winsock2.h> #include <stdio.h> int main() { /* 首先加载套接字 Header: Declared in Winsock2.h. Library: Use Ws2_32.lib. //The WSAStartup function initiates use of Ws2_32.dll by a process int WSAStartup( WORD wVersionRequested, LPWSADATA lpWSAData); The WSAStartup function returns zero if successful. Otherwise, it returns one of the error codes listed in the following. The application or DLL must call WSACleanup to allow the Ws2_32.dll to free any resources for the application. */ WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(1, 1); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ return 0; } if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 ) { /* Tell the user that we could not find a usable */ WSACleanup( ); return 0; } /* 创建套接字: The socket function creates a socket that is bound to a specific service provider. SOCKET socket( int af, int type, int protocol ); Parameters af [in] Address family specification. type [in] Type specification for the new socket. The following are the only two type specifications supported for Windows Sockets 1.1: Type Explanation 流式套接字 SOCK_STREAM Provides sequenced, reliable, two-way, connection-based byte streams with an OOB data transmission mechanism. Uses TCP for the Internet address family. 数据报套接字 SOCK_DGRAM Supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. Uses UDP for the Internet address family. In Windows Sockets 2, many new socket types will be introduced and no longer need to be specified, since an application can dynamically discover the attributes of each available transport protocol through the WSAEnumProtocols function. Socket type definitions appear in Winsock2.h, which will be periodically updated as new socket types, address families, and protocols are defined. protocol [in] Protocol to be used with the socket that is specific to the indicated address family. */ SOCKET socketsrc = socket(AF_INET,SOCK_STREAM,0);//0是自动选择协议 /* 绑定套接字到本地地址上 The bind function associates a local address with a socket. int bind( SOCKET s, const struct sockaddr FAR *name, int namelen ); */ //除了sin_family 其他是网络字节序 //htnol()T function converts a u_long from host to TCP/IP network byte order (which is big-endian). //htnos()function converts a u_short from host to TCP/IP network byte order (which is big-endian). SOCKADDR_IN addrSrc; addrSrc.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSrc.sin_family = AF_INET; //设置地址家族 addrSrc.sin_port=htons(6000); //设置一个端口 bind(socketsrc,(SOCKADDR *)&addrSrc,sizeof(SOCKADDR));//绑定 /* 监听 The listen function places a socket a state where it is listening for an incoming connection. int listen( SOCKET s, int backlog //等待连接的最大队列 ); backlog [in] Maximum length of the queue of pending connections. If set to SOMAXCONN, the underlying service provider responsible for socket s will set the backlog to a maximum reasonable value. There is no standard provision to obtain the actual backlog value. Return Values */ listen(socketsrc,5); /* 等待客户的连接请求和接受客户的数据 The accept function permits an incoming connection attempt on a socket. SOCKET accept( SOCKET s, struct sockaddr FAR *addr,/这个参数输客户端的地址ip信息,而不是服务端的地址信息 int FAR *addrlen ); */ SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); while(1) { SOCKET sockConn = accept(socketsrc,(SOCKADDR*)&addrClient,&len); //连接以后就可以发送数据 char sendBuf[100]; sprintf(sendBuf,"Welcome %s to MyProgram", inet_ntoa(addrClient.sin_addr));//inet_ntoa函数将一个usinged long转换为一个点分十进制地址 send(sockConn,sendBuf,strlen(sendBuf)+1,0); char recvBuf[100]; recv(sockConn,recvBuf,100,0); printf("%s\n",recvBuf); closesocket(sockConn); } return 0; }
这是客户端:
#include <Winsock2.h> #include <stdio.h> int main() { /* 首先加载套接字 Header: Declared in Winsock2.h. Library: Use Ws2_32.lib. //The WSAStartup function initiates use of Ws2_32.dll by a process int WSAStartup( WORD wVersionRequested, LPWSADATA lpWSAData); The WSAStartup function returns zero if successful. Otherwise, it returns one of the error codes listed in the following. The application or DLL must call WSACleanup to allow the Ws2_32.dll to free any resources for the application. */ WORD wVersionRequested; WSADATA wsaData; int err; wVersionRequested = MAKEWORD(1, 1); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { /* Tell the user that we could not find a usable */ return 0; } if ( LOBYTE( wsaData.wVersion ) != 1 || HIBYTE( wsaData.wVersion ) != 1 ) { /* Tell the user that we could not find a usable */ WSACleanup( ); return 0; } SOCKET sockClient = socket(AF_INET,SOCK_STREAM,0); //建立连接 SOCKADDR_IN addSrv;//这个是要设置服务器端的地址结构信息 addSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//这个地址是本地回路地址,代表本机 addSrv.sin_family = AF_INET; addSrv.sin_port = htons(6000); connect(sockClient,(SOCKADDR *)&addSrv,sizeof(SOCKADDR)); char recvBuf[100]; recv(sockClient,recvBuf,100,0); printf("%s\n",recvBuf); send(sockClient,"This is zhangsan",strlen("This is zhangsan")+1,0); closesocket(sockClient); WSACleanup(); return 0; }
运行时,必须先启动服务器端,然后才能显示
然后是 UDP面向无连接的方式 运行上面的,但是 这次可以 服务器端和客户端会话:
首先是服务器端代码:
#include <winsock2.h> #include <stdio.h> void main() { WORD wVersion; WSADATA wsadata; wVersion = MAKEWORD(1,1); int err = WSAStartup(wVersion,&wsadata); if(err != 0) { return; } if(LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion)!= 1) { WSACleanup(); return; } SOCKET sockSRV = socket(AF_INET,SOCK_DGRAM,0); SOCKADDR_IN addrSRV; addrSRV.sin_addr.S_un.S_addr = htonl(INADDR_ANY); addrSRV.sin_family = AF_INET; addrSRV.sin_port = htons(6000); bind(sockSRV,(SOCKADDR *)&addrSRV,sizeof(SOCKADDR)); SOCKADDR_IN addrClient; int len = sizeof(SOCKADDR); char sendBuf[100]; char tempBuf[100]; char recvBuf[100]; while(1) { recvfrom(sockSRV,recvBuf,100,0,(SOCKADDR *)&addrClient,&len); if('q' == recvBuf[0]) { sendto(sockSRV,"q",strlen("q"),0,(SOCKADDR *)&addrClient,len); printf("Char end !\n"); break; } sprintf(tempBuf,"%s say %s",inet_ntoa(addrClient.sin_addr),recvBuf); printf("%s\n",tempBuf); printf("Please Input:\n"); gets(sendBuf); sendto(sockSRV,sendBuf,strlen(sendBuf)+1,0,(SOCKADDR *)&addrClient,len); } closesocket(sockSRV); WSACleanup(); }
然后是客户端代码:
#include <winsock2.h> #include <stdio.h> void main() { WORD wVersion; WSADATA wsadata; wVersion = MAKEWORD(1,1); int err = WSAStartup(wVersion,&wsadata); if(err != 0) { return; } if(LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion)!= 1) { WSACleanup(); return; } SOCKET sockClient = socket(AF_INET,SOCK_DGRAM,0); SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); addrSrv.sin_family = AF_INET; addrSrv.sin_port = htons(6000); int len = sizeof(SOCKADDR); char sendBuf[100]; char tempBuf[200]; char recvBuf[100]; while(1) { printf("Please Input:\n"); gets(sendBuf); sendto(sockClient,sendBuf,strlen(sendBuf)+1,0, (SOCKADDR *)&addrSrv,len); recvfrom(sockClient,recvBuf,100,0,(SOCKADDR *)&addrSrv,&len); if('q' == recvBuf[0]) { sendto(sockClient,"q",strlen("q")+1,0, (SOCKADDR *)&addrSrv,len); printf("Char end!\n"); break; } sprintf(tempBuf,"%s say %s",inet_ntoa(addrSrv.sin_addr),recvBuf); printf("%s\n",tempBuf); } closesocket(sockClient); WSACleanup(); }
相关文章推荐
- Socket网络编程学习笔记(5):发送和接收实体类数据
- socket 发送信息和接收信息 多用于银行通信
- 为什么ServerSocket接收不到客户端Socket发送的信息?
- 26 API-网络编程(网络概述,Socket通信机制,UDP协议发送和接收数据,TCP协议发送和接收数据)
- Socket网络编程学习笔记(5):发送和接收实体类数据
- socket 发送信息和接收信息 多用于银行通信
- [iOS 多线程 & 网络 - 2.0] - 发送接收 服务器信息
- socket接收发送信息
- C# Socket 发送&接收&返回
- Android之Socket通信&&Handler 发送接收多条数据
- C# websocket与html js实现文件发送与接收处理
- QTcpSocket 发送和接收数据的几种方法
- 异步 SOCKET 编程 - 发送和接收数据
- 微信通过openID发送消息/后台post、get提交并接收数据 C# .NET 配置404,500等错误信息 连接字符串
- RocketMQ源码解析:Message发送&接收
- 关于socket应用:一个不断监听一个进程的服务器以及发送信息的客户端 TCP的三次握手和四次挥手
- Android socket 使用PrintWriter和BufferedReader发送和接收出现乱码问题解决
- flex socket.writeObject()发送对象,java接收flex socket发送过来的对象
- 关于servlet服务端接收客户端发送的List<?>数据的问题
- 从缓冲上看阻塞与非阻塞socket在发送接收上的区别