TCP server setup:
- Import module
import socket
- 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协议
- Bind IP and port
sock.bind(("IP",端口号)) #注意里面参数是一个元组
- Set the maximum number of monitors
sock.listen(5) #监听端口
- receive the info
con,addr = sock.accept()
con:接受sock对象,接受对发送信息
addr: ip 和端口号
- Close socket
sock.close()
Construction of TCP client
- Import module
import socket
- Create scoket object
sock =socket.socket(socket.AF_INET,socket.SOCK_STREAM)
- connect to the server
sock.connect(("IP",端口号)) # 同样的这是要元组
- send Message
sock.send("发送信息内容") #注意里面发送的是字节串,不能直接传输字符串 需要encode()
- receive the info
msg = sock.recv(1024) #同样接受的也是字节串,需要进行decode()
- Close socket
sock.close()