网络编程(socket 发送 & 接收信息)

在命令提示符系 通过 C/S 方式发送与接收信息


首先是 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();
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值