zoukankan      html  css  js  c++  java
  • 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++里面的引用形参,嗯,这个示例就这些了!

     

  • 相关阅读:
    Springboot+bootstrap界面版之增删改查及图片上传
    springboot整合Redis
    springboot配置数据库连接池druid、整合mybatis、整合pagehelper
    springboot模板
    springboot入门及配置文件介绍
    java自定义注解
    Git集成idea
    Git的基本操作
    Shiro授权及注解式开发
    《算法》-- 总结
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/2710789.html
Copyright © 2011-2022 走看看