使用socket库
服务端:tcpServer.py
#-*- coding: utf-8 -*- # Filename: tcpServer.py ‘‘‘ server端的socket一般流程是这样: 1.建立一个socket(可以选择socket类型INET,UNIX等,以及连接方式TCP/UDP) 2.使用bind公开一个端口,使得client可以方便连接 3.设置一个listen队列的大小 4.进入一个无限循环,在此无限循环中,使用accept函数来等待客户连接,此函数返回一个新的socket, 对应于客户端的socket,建立通信信道。对socket的处理一般放在外部单独的函数中(并发) 5.通过send()/recv()来对socket进行读写操作 ‘‘‘ import socket import threading class tcpServer(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) self.srvsock.bind((‘‘, 5004)) self.srvsock.listen(1) print ‘Server init‘ def startServer(self): while True: self.clisock, (self.remoteHost, self.remotePort) = self.srvsock.accept() print "[%s:%s] conneted" % (self.remoteHost, self.remotePort) self.clisock.settimeout(5) print "[recv...]" buf = self.clisock.recv(1024) try: if buf == ‘1‘: self.clisock.send(‘[Welcome to Server!]‘) else: self.clisock.send(‘Please go out‘) except socket.timeout: print ‘time out‘ self.clisock.close() def run(self): print ‘Server start‘ self.startServer() def __del__(self): print ‘Server is stop‘ if __name__ == "__main__": s = tcpServer() s.start()
客户端:tcpClient.py
#-*- coding: utf-8 -*- #FileName: TcpClient.py ‘‘‘ 建立一个新的socket 1.使用connect函数与远程主机获得连接 2.在此socket上进行I/O操作 ‘‘‘ import socket def tcpClient(): print ‘client is conneting...‘ clisock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clisock.connect((‘localhost‘, 5004)) import time time.sleep(2) clisock.send(‘1‘) buf = clisock.recv(1024) print ‘recv ‘, buf print ‘client is over‘ clisock.close() if __name__ == "__main__": tcpClient()
使用PythonWin先运行tcpServer,再运行tcpClient
时间: 2024-12-12 14:03:48