#testser.py
#coding=utf-8 from socket import * from time import ctime HOST = "" PORT = 50000 BUFSIZ = 1024 ADDR = (HOST,PORT) # 套接字定义方法:socket(socket_family,socket_type,protocol = 0) # 套接字有两种:基于文件的AF_UNIX(AF_LOCAL为升级版)和基于网络的AF_INET # 每一种套接字都可以分为面向连接的SOCK_STREAM、无连接的SOCK_DGRAM tcpserversock = socket(AF_INET,SOCK_STREAM) # 绑定地址(主机名,端口)到套接字 tcpserversock.bind(ADDR) # listen()表示最多允许多少个连接进来,而后的将被拒绝掉。 tcpserversock.listen(5) while True: print "waiting for connection..." # accept() -> (socket object, address info) Wait for an incoming connection. # Return a new socket representing the connection, and the address of the client. # For IP sockets, the address info is a pair (hostaddr, port). tcpclientsock,addr = tcpserversock.accept() print "...connected from:",addr while True: # recv(buflen[, flags]) -- receive data data = tcpclientsock.recv(BUFSIZ) if not data: break tcpclientsock.send('[%s] %s'% (ctime(),data)) if data == '': tcpclientsock.close() tcpserversock.close()
#testcli.py
from socket import * HOST = "127.0.0.1" PORT = 50000 BUFSIZE = 1024 ADDR = (HOST,PORT) socketclient = socket(AF_INET,SOCK_STREAM) socketclient.connect(ADDR) while True: data = raw_input('>') if not data: break socketclient.send(data) data = socketclient.recv(BUFSIZE) if not data: break print data socketclient.close()