• unix网络编程 chapter4.11代码改写


    sever显示client的IP地址和端口:

    #include"WinSock2.h"
    #include "time.h"
    #include "stdio.h"
    
    #include <iostream>
    
    #pragma comment(lib,"WS2_32")
    
    using namespace std;
    
    const int MaxLine = 1024;
    
    int main()
    {
    	int lRet = 0;
    	WSADATA lWsaData;
    	if ((lRet = WSAStartup(MAKEWORD(2,2), &lWsaData)) != 0)
    	{
    		cout << "Error " << lRet << endl;
    		return 0;
    	}
    
    	int lListen = 0, lConnfd = 0;
    	SOCKADDR_IN lServAddr;
    	char lBuf[MaxLine];
    	time_t lTicks;
    
    	lServAddr.sin_family = AF_INET;
    	lServAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    	lServAddr.sin_port = htons(9999);
    
    	SOCKET lSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    	if (INVALID_SOCKET == lSocket)
    	{
    		cout << "INVALID_SOCKET" << endl;
    		return 0;
    	}
    	bind(lSocket,(sockaddr*)(&lServAddr),sizeof(lServAddr));
    	listen(lSocket,5);
    
    	while(true)
    	{
    		SOCKADDR_IN lClientAddr;
    		int lLen = sizeof(lClientAddr);
    		SOCKET lAcceptedSocket = accept(lSocket,(sockaddr*)&lClientAddr,&lLen);
    		printf("Connection from %s, port %d\n",inet_ntoa(lClientAddr.sin_addr),ntohs(lClientAddr.sin_port));
    		lTicks = time(NULL);
    		sprintf(lBuf, "%.24s\r\n", ctime(&lTicks));
    		char *lTempStr = lBuf;
    		int lSize = strlen(lBuf);
    		for (int i = 0; i < lSize; ++i)
    		{
    			send(lAcceptedSocket,lBuf+i,1,0);
    		}
    		closesocket(lAcceptedSocket);
    	}
    }
    

      

    重点是这句:

    SOCKET lAcceptedSocket = accept(lSocket,(sockaddr*)&lClientAddr,&lLen);

    lAcceptedSocket是sever监听到来自客户端的connection并接受链接后创建的已连接socket,当完成本次client服务时,lAcceptedSocket就会关闭。accept不仅返回了已连接套接字,而且更新了lClientAddr和lLen,这就是书中提到的“值-结果参数”方法,也就是C++里面的引用形参,嗯,这个示例就这些了!

     

  • 相关阅读:
    extjs 为组件动态添加插件
    springboot使用spring-cloud-starter-alibaba-sentinel导致响应变成xml格式
    js 将数据保存到本地
    iframe跨域安全
    nginx url自动301加斜杠
    EXTJS防止表单中回车触发提交
    servlet
    Struts1和Struts2的区别
    AWT和Swing的简记
    sleep()和wait()
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/2710789.html
Copyright © 2020-2023  润新知