server:
<span style="font-family:Courier New;font-size:18px;"><span style="font-family:Courier New;font-size:14px;">import socket
import sys
HOST=''
PORT=21567
BUFSIZE=1024
ADDR=(HOST,PORT)
try:
tcpSerSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('socket created.')
except (socket.error,msg):
print('failed to create socket.Error code:'+ str(msg[0]) + ' , Error message : ' + msg[1])
sys.exit()
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5) # allow 5 connection
while True:
print('waiting for connetion...')
tcpCliSock,addr=tcpSerSock.accept()
print('...connected from:',addr)
while True:
data=tcpCliSock.recv(BUFSIZE).decode()
print(data)
if not data:
break
tcpCliSock.send(('you typed '+data).encode())
tcpCliSock.close() #diff here.see python core programming
tcpSerSock.close()
</span></span>
client:
<span style="font-family:Courier New;font-size:18px;"><span style="font-family:Courier New;font-size:14px;">import socket
import sys
HOST='localhost'
PORT=21567 #must be same to server's
BUFSIZE=1024
ADDR=(HOST,PORT)
try:
tcpCliSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print('socket created.')
except (socket.error,msg):
print('failed to create socket.Error code:'+ str(msg[0]) + ' , Error message : ' + msg[1])
sys.exit()
tcpCliSock.connect(ADDR)
while True:
data=input('>')
if not data: #enter to end
break
tcpCliSock.send(data.encode())
data=tcpCliSock.recv(BUFSIZE).decode() #since 'str' is different from unicodestring in python3
if not data: #recv err,end
break
print(data)
tcpCliSock.close()
</span></span>
建议在cmd下运行