python通过socket进行通信的简单范例,带客户端和服务器端
服务器端
from socket import * import thread PORT=5648 BUFSIZE=1024 def th(): while True: data=raw_input("") if not data: break tcpCliSock.send(data) ADDR=("",PORT) tcpSerSock=socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) print "waiting fot connection..." tcpCliSock,addr=tcpSerSock.accept() print "connection from :%s" % str(addr) thread.start_new_thread(th,()) while True: data=tcpCliSock.recv(BUFSIZE) if not data: break print data tcpSerSock.close()
客户端
from socket import * import thread HOST='localhost' PORT=5648 BUFSIZE=1024 ADDR=(HOST,PORT) def th(sock): while True: data=raw_input("") if not data: break sock.send(data) tcpCliSock=socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) thread.start_new_thread(th,(tcpCliSock,)) while True: data=tcpCliSock.recv(BUFSIZE) print data tcpCliSock.close()