Python implementation of TCP steps

TCP server setup:

  1. Import module
   import socket
  1. Create socket object
sock = socket.socket(socket_family,socet_type)
	参数:
		socket_family
			socket.AF_INET IPV4
			socket.AF_INET6 IPV6
			socket.AF_UNIX  unix 系统内部传输
		socket_type
			socket.SOCK_STREAM  TCP协议
			socket.SOCK_DGRAM    UDP协议
  1. Bind IP and port
 sock.bind(("IP",端口号))  #注意里面参数是一个元组
  1. Set the maximum number of monitors
sock.listen(5) #监听端口
  1. receive the info
con,addr = sock.accept()
	con:接受sock对象,接受对发送信息
	addr: ip 和端口号
  1. Close socket
sock.close()

Construction of TCP client

  1. Import module
import socket
  1. Create scoket object
sock =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1. connect to the server
sock.connect(("IP",端口号)) # 同样的这是要元组
  1. send Message
sock.send("发送信息内容") #注意里面发送的是字节串,不能直接传输字符串 需要encode()
  1. receive the info
 msg = sock.recv(1024)  #同样接受的也是字节串,需要进行decode()
  1. Close socket
sock.close()

Guess you like

Origin blog.csdn.net/NewDay_/article/details/108944083