1. 程式人生 > >2017.8.22 用python實現簡單基於TCP/IP的客戶端與伺服器端

2017.8.22 用python實現簡單基於TCP/IP的客戶端與伺服器端

伺服器端
import socket
serversocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serversocket.bind(('127.0.0.1',8000))
serversocket.listen(1)
clientsocket,clientaddress=serversocket.accept()
print('Connection from ',clientaddress)
while 1:
    data=clientsocket.recv(1024)
    if not data:
        break
    print('Received from client: ',repr(data.decode()))
    newdata=input('replt >>')
    #print('Echo: ',repr(newdata))
    clientsocket.send(newdata.encode())
clientsocket.close()
serversocket.close()

客戶端
import socket
clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientsocket.connect(('127.0.0.1',8000))
while 1:
    data=input('reply >>')
    clientsocket.send(data.encode())
    if not data:
        break
    newdata=clientsocket.recv(1024)
    print('Received: ',repr(newdata.decode()))
clientsocket.close()