1. 程式人生 > >python socket簡單的伺服器端和客戶端

python socket簡單的伺服器端和客戶端

import socket

L_HOST = "" #local IP
L_PORT = 2080 #local port
L_BUFSIZ = 255
L_ADDR = (L_HOST,L_PORT)

S_HOST = "192.168.31.202" #senser IP
S_PORT = 8080 #senser port
S_BUFSIZ = 255
S_ADDR = (S_HOST,S_PORT)

sensorSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sensorSocket.connect(S_ADDR)

print("******connect sensor at ",S_HOST,S_PORT)

serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind(L_ADDR)
serverSocket.listen(1)

print("******wait for robot...******")

robotSocket,robotAddr = serverSocket.accept()

print("******connect robot at ",robotAddr,L_PORT)

print("******START******")

i=0;
while True:
    
    sensorData = sensorSocket.recv(S_BUFSIZ)
    i=i+1;
    print(i)
    if sensorData:
        print("***receive from sensor: "+str(sensorData,encoding="utf-8"))
        print("type: "+str(type(sensorData)))

    robotSocket.send(sensorData)
    print("send to robot success.")

    robotData = robotSocket.recv(L_BUFSIZ)
    i=i+1;
    print(i)
    if robotData:
        print("***receive from robot: "+str(robotData,encoding="utf-8"))
        print("type: "+str(type(robotData)))

    sensorSocket.send(robotData)
    print("send to sensor success.")
 

使用tcp除錯助手:

1、python的socket.accept ,socket.recv會一直掛起等待

2、在此期間保持的連結收到的資料會被壓入BUFFER中,在下次recv時一起讀入。