1. Client
Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #建立TCP连接
S.connect (' 192.168.1.109 ', 1111) #连接服务器, requires the server's address and port
Print (' This is the client! ‘)
While True:
t = input () #输入
S.send (T.encode (' UTF8 ')) #发送t的utf8格式数据
If T = = ' exit ': #如果发现是exit
Break
t= ' server: ' +s.recv (1024x768). Decode (' UTF8 ') #收到服务器来的数据
If T = = ' exit ': #如果服务器来的是exit, exit the loop
Break
Print (t)
Print (' Disconnect! ‘)
S.close ()
2. Service-side
Import socket
s = Socket.socket (socket.af_inet,socket. SOCK_STREAM) #TCP通讯 to ensure that data reaches
S.bind ((' 192.168.1.109 ', 1111)) #自身服务器地址, with open ports
S.listen (5) #监听数
Print (' This is the server! ‘)
Print (' Please wait ... ')
Connect,address = s.accept () #接受客户端的连接:
Print ("Connection Successful! ")
While True:
t = ' client: ' +connect.recv (1024x768). Decode (' UTF8 ') #服务端先接收信息, and parse UTF8
If T = = ' exit ': #如果接收到的是exit
Break #退出循环
Print (t) #不然就打印出来信息
t = input () #然后服务器输入
If T = = ' exit ': #如果是exit, exit the loop
Break
Connect.send (T.encode (' UTF8 ')) #使connect收发数据 (sent to connected socket data)
Print (' Disconnect! ‘)
S.close ()
#先使服务端运行, after running the client
"Python sockets" socket programming