半开放和半关闭tcp连接的Python代码

时间:2018-01-03 18:27:36

标签: python sockets tcp

我是python的新手并尝试创建一个测试平台,我在客户端和服务器之间有一个TCP半开放和TCP半关闭情况。 服务器代码:

def recv_end(the_socket):
 End='SERVER WRONG MARKER'
 total_data=[];data='';got_end=False
 while True:
  data=the_socket.recv(8192)
  if not data: break
  if End in data:
   total_data.append(data[:data.find(End)])
   got_end=True
   break
  total_data.append(data)
  if len(total_data)>1:
   #check if end_of_data was split
   last_pair=total_data[-2]+total_data[-1]
   if End in last_pair:
    total_data[-2]=last_pair[:last_pair.find(End)]
    total_data.pop()
    got_end=True
    break
 return (got_end,''.join(total_data))

def basic_server(sock):
 got=[]
 got_end,data = recv_end(sock)
 if not got_end:
  sock.send('ERROR:no end!') #<--- not possible w/close()
 else: sock.sendall(data*2)
 sock.shutdown(1)
 sock.close()

import socket
Port=4444
def start_server():
 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 sock.bind(('',Port))
 sock.listen(5)
 print 'started on',Port
 while True:
  newsock,address=sock.accept()
  basic_server(newsock)

def send_data(data):
 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 sock.connect(('localhost',Port))
 print 'connected'
 sock.sendall(data+'CLIENT WRONG MARKER')
 print 'sent',data
 sock.shutdown(1)
 print 'shutdown'
 result=[]
 while True:
  got=sock.recv(2)
  if not got: break
  result.append(got)
  sock.close()
 return ''.join(result)

if __name__=='__main__':
    start_server()

客户端代码:

import socket
def send_data(data):
 sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 sock.connect(('localhost',Port))
 print 'connected'
 sock.sendall(data+'CLIENT WRONG MARKER')
 print 'sent',data
 sock.shutdown(1)
 print 'shutdown'
 result=[]
 while True:
  got=sock.recv(2)
  if not got: break
  result.append(got)
  sock.close()
 return ''.join(result)

def shut_serv_end():
 data=('a1234','b1234','c1234','d1234','e1234')
 for d in data:
  print shut_srv.send_data(d)

我正在尝试使用有三个选项的shutdown命令:0 =完成接收,1 =完成发送,2 =两者

在上面的代码中,重点是1.代码没有按预期工作。这意味着,当我进行数据包捕获时,我看不到半开连接。任何人都可以提供一些提示或示例,说明如何实现它或我在做什么错误?

0 个答案:

没有答案