Python使用TCP通讯例子

TCP通讯十分常用,对应Python库为socket

import json
import socket 

tcp_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_SNDBUF,65536)
tcp_server.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,65536)
print(f'Send Buf: {tcp_server.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)}') 
print(f'Recv Buf: {tcp_server.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)}') 

tcp_server.bind(('127.0.0.1', 2022))
tcp_server.listen(128)

print(f'Server IP: {tcp_server.getsockname()}')

while True:
    client_socket, client_addr = tcp_server.accept()
    data = client_socket.recv(1024)
    print(f'Request: {data.decode()}')
    data = json.loads(data)
    data['status'] = 'ok'
    data = json.dumps(data)
    client_socket.send(data.encode())

上段为TCP服务端,下段为TCP客户端,如果只需要单次连接的话去掉循环就好;

import time
import json
import socket

while True:
	server_addr = ('127.0.0.1', 2022) 
	tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
	tcp_client.settimeout(5)
	tcp_client.connect(server_addr)
	data = json.dumps({'message':'status'})

	tcp_client.send(data.encode())
	data = tcp_client.recv(1024)
	print(f'Respond: {data.decode()}')    
	tcp_client.close()
	time.sleep(1)

你可能感兴趣的:(python,tcp)