原文:https://www.etdev.net/thread-60-1-1.html
1. 服务端Server
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import threading
import time
def tcp_thread(sock,addr):
print('new connection from %s,%s'%addr)
log('new connection from %s,%s'%addr)
sock.send(b'welcome')
try:
while True:
#receiving up to 1k bytes at a time
data=sock.recv(1024)
if not data or data.decode('utf-8')=='exit':
break
sock.send(data)
print(data.decode('utf-8'))
(ip,port)=addr
log('%s:%s %s'%(ip,port,data.decode('utf-8')))
sock.close()
except Exception as err:
print(err)
finally:
sock.close()
def start_tcp_server(ip,port):
#create socket
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#bind port
addr=(ip,port)
server.bind(addr)
#starting listening,allow 10 connection
try:
print ("starting listen on ip %s, port %s"%addr)
server.listen(10)
except socket.err as e:
print ("fail to listen on port %s"%e)
sys.exit(1)
#accept client connect
while True:
print ("\r\nwaiting for client connection")
client,addr=server.accept()
#create a thread to handle tcp link
thread=threading.Thread(target=tcp_thread,args=(client,addr))
thread.start()
def log(msg):
tm=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
#writes the data to file
with open('server-debug.log','a') as f:
f.write('[%s] %s\r\n'%(tm,msg))
if __name__ == '__main__':
host=socket.gethostname()
ip=socket.gethostbyname(host)
start_tcp_server(ip,6800)
#start_tcp_server('0.0.0.0',6800)
2. 客户端Client
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import datetime
#create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostname()
ip=socket.gethostbyname(host)
#connect to server
local=False
if local:
s.connect((ip,6800))
else:
s.connect(('47.98.163.223',6800))
#send test data
#s.send(b'tcp test')
#receive data
buf = []
while True:
#receiving up to 1k bytes at a time
d = s.recv(1024)
if d:
buf.append(d)
#print(buf)
print(d)
msg = input('please input data\r\n>>')
s.send(msg.encode('utf-8'))
#break
else:
break
s.close()
data = b''.join(buf)
print(data)
#writes the data to file
tm=datetime.datetime.now()
with open('client-debug.log','a') as f:
f.write('[%s] %s\r\n'%(tm,data))