服务器端代码:
1 #!/usr/bin/python 2 3 import time, socket, threading 4 5 # thread handle function 6 def tcplink(sock, addr): 7 print 'Accept new connection from %s:%s...' % addr 8 sock.send('Welcome!') 9 while True: 10 data = sock.recv(1024) 11 time.sleep(1) 12 if data == 'exit' or not data: 13 break 14 sock.send('Hello, %s!' % data) 15 sock.close() 16 print 'Connection from %s:%s closed.' % addr 17 18 # create socket object 19 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 20 # listen port 21 s.bind(('127.0.0.1', 9999)) 22 # start listen 23 s.listen(5) 24 # print prompt 25 print 'Waiting for connection...' 26 27 while True: 28 # accept a new connection 29 sock, addr = s.accept() 30 # create new thread to handle tcp connection 31 t = threading.Thread(target=tcplink, args=(sock, addr)) 32 t.start() 33 34
客户端代码:
1 #!/usr/bin/python 2 3 # import module 4 import socket 5 6 # create TCP object 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 # connect sina 9 s.connect(('127.0.0.1', 9999)) 10 # receive welcome 11 print s.recv(1024) 12 13 for data in ['zjw', 'ygl', 'lele']: 14 # send data 15 s.send(data) 16 print s.recv(1024) 17 while True: 18 data = 1
设计思路还是那样的,服务器端监听固定端口,等待连接,客户端来连接,然后互相发送消息