connect, accept .listen, send ,recv, setblock等系列的封装

bool CSock::Listen(int nConnectionBacklog)
{
 return listen(m_sock, nConnectionBacklog) != SOCKET_ERROR;
}

bool CSock::Accept(CKKSock &rConnectedSocket, SOCKADDR *lpSockAddr, int *lpSockAddrLen)
{
 SOCKET hTemp = accept(m_sock, lpSockAddr, lpSockAddrLen);

 if (hTemp == INVALID_SOCKET)
 {
  //DWORD dwProblem = GetLastError();
  rConnectedSocket.m_sock = INVALID_SOCKET;
  //SetLastError(dwProblem);
 }
 else
 {
  rConnectedSocket.m_sock = hTemp;
 }
 return (hTemp != INVALID_SOCKET);
}

bool CSock::Accept(SOCKET &socket, SOCKADDR *lpSockAddr, int *lpSockAddrLen)
{
 socket = accept(m_sock, lpSockAddr, lpSockAddrLen);

 if (socket == INVALID_SOCKET)
 {
  DWORD dwProblem = GetLastError();
  socket = INVALID_SOCKET;
  SetLastError(dwProblem);
 }
 return (socket != INVALID_SOCKET);
}

int CSock::Send(const void *lpBuf, int nBufLen, int nFlags)
{
 return send(m_sock, (LPSTR)lpBuf, nBufLen, nFlags);
}

int CSock::Receive(void *lpBuf, int nBufLen, int nFlags)
{
 return recv(m_sock, (LPSTR)lpBuf, nBufLen, nFlags);
}

bool CSock::IsInvaild()
{
 return m_sock == INVALID_SOCKET;
}

void CSock::SetBlock(bool block)

 u_long b = block ? 0 : 1;
 ioctlsocket(m_sock, FIONBIO, &b);
}

int CSock::Connect(LPCTSTR lpszHostAddress, UINT nHostPort, bool bBlock)
{
 if (m_sock == INVALID_SOCKET)
 {
  Create(AF_INET, SOCK_STREAM, 0);
 }
 
 SetBlock(bBlock);
 ASSERT(lpszHostAddress != NULL);

 SOCKADDR_IN sockAddr;
 memset(&sockAddr,0,sizeof(sockAddr));

 LPSTR lpszAscii = T2A((LPTSTR)lpszHostAddress);
 sockAddr.sin_family = AF_INET;
 sockAddr.sin_addr.s_addr = inet_addr(lpszAscii);

 if (sockAddr.sin_addr.s_addr == INADDR_NONE)
 {
  LPHOSTENT lphost;
  lphost = gethostbyname(lpszAscii);
  if (lphost != NULL)
   sockAddr.sin_addr.s_addr = ((LPIN_ADDR)lphost->h_addr)->s_addr;
  else
  {
   WSASetLastError(WSAEINVAL);
   return -1;
  }
 }

 sockAddr.sin_port = htons((u_short)nHostPort);

 return connect(m_sock, (SOCKADDR*)&sockAddr, sizeof(sockAddr));

 /*u_long start = GetTickCount();
 int result;
 while(1)//POLL_TIMEOUT
 {
  result = m_sock.Wait(5000, WAIT_CONNECT);
  if (result == WAIT_ERROR)
   return -1;
  if (result & WAIT_CONNECT)
   break;
  if(result == 10060 || (start + 30000) > GetTickCount())
  {
   // Connection timeout
   //fail(STRING(CONNECTION_TIMEOUT));
   return 0;
  }
 }
 return 1;*/
}

void CSock::Attach(SOCKET sock)
{
 m_sock = sock;
}
/*******************************
*   设置socket的缓冲buffer的大小
*  add by gavin on 2006.3.6
*******************************/
void CSock::SetSockBuff(long nSockRecvBufferLen,long nSockSendBufferLen)
{
 int   nTimeOut = 500;
 int   nErrorNum = 0;
 int   nFlagValue = 0;
 setsockopt(m_sock,SOL_SOCKET,SO_SNDBUF,(char*)&nSockSendBufferLen,sizeof(int));
 setsockopt(m_sock,SOL_SOCKET,SO_RCVBUF,(char*)&nSockRecvBufferLen,sizeof(int));
 nFlagValue = setsockopt(m_sock,SOL_SOCKET,SO_SNDTIMEO,(char*)&nTimeOut,sizeof(nTimeOut));//设置发送超时
 nFlagValue = setsockopt(m_sock,SOL_SOCKET,SO_RCVTIMEO,(char*)&nTimeOut,sizeof(nTimeOut));//设置发送超时
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
优化并改编以下代码,使其和原来有部分出入但实现效果相同: 1. import socket 2. 3. 4. def client(): 5. # 创建套接字 6. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7. # 连接服务器 8. ip = input("Please input the receiver's ipv4 address:") 9. sock.connect((ip, 14000)) 10. # 发送文件名 11. filename = input("Please input the filename:") 12. sock.send(filename.encode()) 13. # 接收服务器返回的消息 14. data = sock.recv(1024) 15. print(data.decode()) 16. # 发送文件内容 17. with open(filename, 'rb') as f: 18. for line in f: 19. sock.send(line)20. print('File has sent successfully') 21. # 关闭套接字 22. sock.close() 23. 24. 25.def server(): 26. # 创建套接字 27. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 28. # 绑定地址和端口号 29. 30. sock.bind(('', 14000)) 31. # 监听连接请求 32. sock.listen(5) 33. while True: 34. # 接受连接请求 35. conn, addr = sock.accept() 36. print('The connection has been established') 37. # 接收文件名 38. filename = conn.recv(1024).decode() 39. print(filename) 40. # 发送消息到客户端 41. conn.send('Got the file name'.encode()) 42. # 接收文件内容并写入文件 43. with open(filename, 'wb') as f: 44. while True: 45. data = conn.recv(1024) 46. if not data: 47. break 48. f.write(data) 49. print('File has received successfully') 50. # 关闭连接套接字 51. conn.close() 52. 53. 54.if name == 'main': 55. while True: 56. answer = input("This is a simple program relying on the Tc p protocol, \n if you want to send the file," 57. "please input 1, \n if you want to receive the file, please input 2, \n if you want exit, " 58. "please input 0: \n") 59. if answer == '0': 60. break 61. if answer == '1': 4162. client() 63. if answer == '2': 64. server()
05-24
以下是优化并改编后的代码: ``` import socket def send_file(ip, filename): # 创建套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 连接服务器 sock.connect((ip, 14000)) # 发送文件名 sock.send(filename.encode()) # 接收服务器返回的消息 data = sock.recv(1024) print(data.decode()) # 发送文件内容 with open(filename, 'rb') as f: for line in f: sock.send(line) print('File has been sent successfully') # 关闭套接字 sock.close() def receive_file(): # 创建套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 绑定地址和端口号 sock.bind(('', 14000)) # 监听连接请求 sock.listen(5) while True: # 接受连接请求 conn, addr = sock.accept() print('The connection has been established') # 接收文件名 filename = conn.recv(1024).decode() print(filename) # 发送消息到客户端 conn.send('Got the file name'.encode()) # 接收文件内容并写入文件 with open(filename, 'wb') as f: while True: data = conn.recv(1024) if not data: break f.write(data) print('File has been received successfully') # 关闭连接套接字 conn.close() if __name__ == '__main__': while True: answer = input("This is a simple program relying on the TCP protocol, \n if you want to send the file," "please input 1, \n if you want to receive the file, please input 2, \n if you want exit, " "please input 0: \n") if answer == '0': break if answer == '1': ip = input("Please input the receiver's ipv4 address:") filename = input("Please input the filename:") send_file(ip, filename) if answer == '2': receive_file() ``` 优化和改编后的代码保持了原有代码的功能,但是进行了一些优化和改进。具体如下: 1. 将客户端和服务端的代码分别封装send_file()和receive_file()两个函数,方便调用和管理。 2. 在主函数中,根据用户输入的不同数字,选择执行发送文件或接收文件的函数。同时,添加了退出程序的选项。 3. 在发送文件时,将获取IP和文件名的代码放在函数外部进行,以便多次调用send_file()函数。 4. 修改了输出信息,使其更加准确和易于理解。 5. 对代码进行了格式化和注释,使其更加易读和易懂。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值