from socket import * from time import ctime HOST = '' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpSerSock = socket(AF_INET,SOCK_STREAM) tcpSerSock.bind( ADDR) tcpSerSock.listen(5) while True: print 'waiting for connection......' tcpCliSock,addr = tcpSerSock.accept( ) print '......connected from:',addr while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s]%s' %(ctime(),data)) tcpCliSock.close( ) tcpSerSock.close()
1 from socket import * 2 3 HOST = 'localhost' 4 PORT = 21567 5 BUFSIZ = 1024 6 ADDR = (HOST,PORT) 7 8 tcpCliSock = socket(AF_INET,SOCK_STREAM) 9 tcpCliSock.connect(ADDR) 10 11 while True: 12 data = raw_input('>') 13 if not data: 14 break 15 tcpCliSock.send(data) 16 data = tcpCliSock.recv(BUFSIZ) 17 if not data: 18 break 19 print data 20 21 tcpCliSock.close()
1 from socket import * 2 from time import ctime 3 4 HOST = '' 5 PORT = 21567 6 BUFSIZ = 1024 7 ADDR = (HOST,PORT) 8 9 udpSerSock = socket(AF_INET,SOCK_DGRAM) 10 udpSerSock.bind(ADDR) 11 12 while True: 13 print 'waiting for message......' 14 data,addr = udpSerSock.recvfrom(BUFSIZ) 15 udpSerSock.sendto('[%s] %s' % (ctime,data) ,addr) 16 print '......received from and returned to:',addr 17 18 udpSerSock.close()
1 from socket import * 2 3 HOST = 'localhost' 4 PORT = "21567" 5 BUFSIZ = 1024 6 ADDR = (HOST,PORT) 7 8 udpCliSock = socket(AF_INET,SOCK_DGRAM) 9 10 while Trus: 11 data = raw_input('>') 12 if not data: 13 break 14 udpCliSock.sendto(data,ADDR) 15 data,ADDR = udpCliSock.recvfrom(BUFSIZ) 16 if not data: 17 break 18 print data 19 20 udpCliSock.close()
類 | 描述 |
BaseServer | 包含服務器核心功能與混合(mix-in)類掛鉤;這個類只用於派生,因此不會生成這個類的實例;能夠考慮使用TCPServer和UDPServer |
TCPServer/UDPServer | 基本的網絡同步TCP/UDP服務器 |
UnixStreamServer/UnixDatagramServer | 基本的基於文件同步TCP/UDP服務器 |
ForkingMixIn/ThreadingMixIn | 實現了核心的進程化或線程化的功能;做爲混合類,與服務器類一併使用以提供一些異步特性;這個類不會直接實例化。 |
ThreadingTCPServer/ThreadingUDPServer | ThreadingMixIn和TCPServer/UDPServer的組合 |
BaseRequestHandler | 包含處理服務器請求的核心功能,這個類只用於派生,因此不會生成這個類的實例能夠考慮使用StreamRequestHandler 或 DatagramRequestHandler |
StreamRequestHandler/DatagramRequestHandler | 用於TCP/UDP服務器處理工具 |
from SocketServer import (TCPServer as TCP,StreamRequsetHandler as SRH) from time import ctime HOST = '' PORT = 21567 ADDR = (HOST,PORT) class MyRequestHandler(SRH): def handle(self): print '......connected from:',self.client_address self.wfile.write('[%s]%s' % (ctime(),self.rfile.readline())) tcpServ = TCP(ADDR,MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever( )
1 from socket import * 2 3 HOST = 'localhost' 4 PORT = 21567 5 BUFSIZ = 1024 6 ADDR = (HOST,PORT) 7 8 while True: 9 tcpCliSock = socket(AF_INET,SOCK_STREAM) 10 tcpCliSock.connect(ADDR) 11 data = raw_input('>') 12 if not data: 13 break 14 tcpCliSock.send('%s\r\n' %data) 15 data = tcpCliSock.recv(BUFSIZ) 16 if not data: 17 break 18 print data.strip() 19 tcpCliSock.close() 20
1 from socket import * 2 from time import ctime 3 4 5 HOST = '' 6 PORT = 21567 7 BUFSIZ = 1024 8 ADDR = (HOST,PORT) 9 10 11 tcpSerSock = socket(AF_INET,SOCK_STREAM) 12 tcpSerSock.bind(ADDR) 13 tcpSerSock.listen(5) 14 15 16 while True: 17 print 'waitiing for connection...' 18 tcpCliSock,addr = tcpSerSock.accept() 19 print '...connected from:',addr 20 21 22 while True: 23 data = tcpCliSock.recv(BUFSIZ) 24 if not data: 25 break 26 tcpCliSock.send('[%s] %s' % (ctime(),data)) 27 28 tcpSerSock.close() 29 30
1 from socket import * 2 import time,os 3 4 5 HOST = '' 6 PORT = 21567 7 BUFSIZ = 1024 8 ADDR = (HOST,PORT) 9 10 11 tcpSerSock = socket(AF_INET,SOCK_STREAM) 12 tcpSerSock.bind(ADDR) 13 tcpSerSock.listen(5) 14 15 16 while True: 17 print 'waitiing for connection...' 18 tcpCliSock,addr = tcpSerSock.accept() 19 print '...connected from:',addr 20 21 while True: 22 data = tcpCliSock.recv(BUFSIZ) 23 data = data.strip() 24 if not data: 25 break 26 if data == "date": 27 tcpCliSock.send('%s' % (time.ctime(time.time()))) 28 elif data == "os": 29 tcpCliSock.send('%s' % (os.name)) 30 elif data == "ls": 31 tcpCliSock.send('%s' % (os.listdir(os.curdir))) 32 else: 33 tcpCliSock.send('[%s] %s' % (time.ctime(),data)) 34 35 36 tcpSerSock.close()
1 from socket import * 2 from time import ctime 3 4 5 HOST = "localhost" 6 7 PORT = getservbyname("daytime","udp") 8 9 BUFSIZ = 1024 10 11 ADDR = (HOST,PORT) 12 13 udpSerSock = socket(AF_INET,SOCK_DGRAM) 14 15 udpSerSock.bind(ADDR) 16 17 while True: 18 print "waiting for message..." 19 data,addr = udpSerSock.recvfrom(BUFSIZ) 20 udpSerSock.sendto("[%s]%s" % (ctime(), data),addr) 21 print "...received from and returned to:",addr 22 23 24 udpSerSock.close 25
1 from socket import * 2 from time import ctime 3 4 5 HOST = "localhost" 6 PORT = getservbyname("daytime","udp") 7 8 BUFSIZ = 1024 9 10 ADDR = (HOST,PORT) 11 12 udpCliSock = socket(AF_INET,SOCK_DGRAM) 13 14 15 while True: 16 data = raw_input(">") 17 if not data: 18 break 19 udpCliSock.sendto(data,ADDR) 20 data,ADDR = udpCliSock.recvfrom(BUFSIZ) 21 if not data: 22 break 23 print data 24 25 tcpCliSock.close()
from socket import * HOST = "localhost" PORT = 23346 BUFSIZ = 1024 ADDR = (HOST,PORT) tcpCliSock = socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data = raw_input("client>") if not data: continue tcpCliSock.send(data) while True: data = tcpCliSock.recv(BUFSIZ) if not data: continue else: print "server>",data break tcpCliSock.close()
1 from socket import * 2 3 HOST = "localhost" 4 PORT = 23346 5 BUFSIZ = 1024 6 ADDR = (HOST,PORT) 7 8 9 tcpServSock = socket(AF_INET,SOCK_STREAM) 10 tcpServSock.bind(ADDR) 11 tcpServSock.listen(5) 12 13 14 15 while True: 16 print "waiting for connection..." 17 tcpCliSock,addr = tcpServSock.accept() 18 print "connected from:",addr 19 20 while True: 21 data = tcpCliSock.recv(BUFSIZ) 22 if not data: 23 continue 24 print "client>",data 25 data = raw_input("server>") 26 tcpCliSock.send(data) 27 28 tcpServSock.close() 29
1 #!/usr/bin/env python 2 #-*- coding:utf-8 -*- 3 import socket,traceback,os 4 from threading import * 5 6 host = 'localhost' 7 port = 51423 #監聽全部的接口 8 9 #接受消息的線程 10 def handlerecv(clientsock): 11 print "New child",currentThread().getName() 12 print "Got connection from",clientsock.getpeername() 13 while True: 14 data = clientsock.recv(4096) 15 if not len(data): 16 break 17 print data 18 clientsock.close() 19 20 #發送消息的線程 21 def handlesend(clientsock): 22 while True: 23 data = raw_input(">") 24 data = data + "\n"; #加上換行,好看一點。 25 clientsock.sendall(data) 26 #關閉鏈接 27 clientsock.close() 28 29 #創建套接字 30 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 31 s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) 32 s.bind((host,port)) 33 s.listen(1) 34 35 while True: 36 try: 37 clientsock,clientaddr = s.accept() 38 except KeyboardInterrupt: 39 raise 40 except: 41 traceback.print_exc() 42 continue 43 44 t = Thread(target = handlerecv,args=[clientsock]) 45 t.setDaemon(1) 46 t.start() 47 48 r = Thread(target = handlesend,args=[clientsock]) 49 r.setDaemon(1) 50 r.start() 51 52 53 54
1 #!/usr/bin/env python 2 #-*-coding:utf-8-*- 3 4 from socket import * 5 import sys 6 from threading import * 7 8 if(len(sys.argv) < 3): 9 HOST = 'localhost' 10 PORT = 51423 11 else: 12 HOST = sys.argv[1] 13 PORT = int(sys.argv[2]) 14 15 BUFSIZ = 1024 16 ADDR = (HOST,PORT) 17 18 def handlesend(tcpCliSock): 19 while True: 20 sdata = raw_input('> ') 21 if not sdata: 22 break 23 tcpCliSock.send(sdata) 24 25 tcpCliSock.close() 26 27 tcpCliSock = socket(AF_INET,SOCK_STREAM) 28 tcpCliSock.connect(ADDR) 29 30 #創建發送消息的線程 31 s = Thread(target = handlesend,args=[tcpCliSock]) 32 s.setDaemon(1) 33 s.start() 34 35 while True: 36 rdata = tcpCliSock.recv(BUFSIZ) 37 if not rdata: 38 break 39 print rdata 40 tcpCliSock.close()
1 #!/usr/bin/env python 2 # _*_ coding: utf8 _*_ 3 4 from socket import * 5 from time import ctime 6 import threading 7 from string import split 8 9 HOST = '' 10 PORT = 21567 11 BUFSIZE = 1024 12 ADDR = (HOST, PORT) 13 14 def Deal(sck, username, room): 15 while True: 16 data = sck.recv(BUFSIZE) 17 for i in clients[room].iterkeys(): 18 if i <> username: 19 if data <> "quit": 20 clients[room][i].send("[%s] %s: %s" %(ctime(), username, data)) 21 else: 22 clients[room][i].send("用戶%s在%s退出房間%s" %(username, ctime(), room )) 23 if data == "quit": 24 del clients[room][username] 25 sck.send(data) 26 sck.close() 27 break 28 29 30 chatSerSock = socket(AF_INET, SOCK_STREAM) 31 chatSerSock.bind(ADDR) 32 chatSerSock.listen(5) 33 34 clients = {"":{},} 35 36 while True: 37 print 'waiting for connection...' 38 chatCliSock, addr = chatSerSock.accept() 39 print "...connected romt: ", addr 40 data = chatCliSock.recv(BUFSIZE) 41 username, room = split(data) 42 print username 43 if not clients.has_key(room): 44 clients[room] = {} 45 if clients[room].has_key(username): 46 chatCliSock.send("reuse") 47 chatCliSock.close() 48 else: 49 chatCliSock.send("success") 50 clients[room][username] = chatCliSock 51 t = threading.Thread(target=Deal, args=(chatCliSock, username, room)) 52 t.start() 53 54 chatSerSock.close()
客戶端 cc.pyhtml
1 #!/usr/bin/env python 2 # _*_ coding: utf8 _*_ 3 4 from socket import * 5 from time import ctime 6 import threading 7 import random 8 from sys import argv, exit, stdout 9 from getopt import gnu_getopt, GetoptError 10 11 12 13 14 help_info = ["cs.py [ -h | --help | -u | --username] username", 15 "\t-h or --help\t顯示幫助信息", 16 "\t-u or --username\指定用戶名", 17 "\t-r or --room\t指定房間"] 18 def help(): 19 for i in help_info: 20 print i 21 22 23 24 def Send(sck, test): 25 while True: 26 data = raw_input('>') 27 sck.send(data) 28 if data == "quit": 29 break 30 def Recieve(sck, test): 31 while True: 32 data = sck.recv(BUFSIZ) 33 if data == "quit": 34 sck.close() 35 break 36 str = "\n" + data + "\n>" 37 stdout.write(str) 38 39 HOST = 'localhost' 40 PORT= 21567 41 BUFSIZ = 1024 42 ADDR = (HOST, PORT) 43 threads = [] 44 45 if __name__ == "__main__": 46 # 解析命令行參數 47 try: 48 opts, args = gnu_getopt(argv[1:], "hu:r:", ["help", "username=", "room="]) 49 except GetoptError, err: 50 print str(err) 51 help() 52 exit(2) 53 username = "" 54 room = "" 55 for o, a in opts: 56 if o in ("-h", "--help"): 57 help() 58 exit(0) 59 elif o in ("-u", "--username"): 60 username = a 61 elif o in ("-r", "--room"): 62 room = a 63 else: 64 print "未知選項" 65 help() 66 exit(2) 67 if not username or not room: 68 help() 69 exit(2) 70 chatCliSock = socket(AF_INET, SOCK_STREAM) 71 chatCliSock.connect(ADDR) 72 chatCliSock.send("%s %s" %(username, room)) 73 data = chatCliSock.recv(BUFSIZ) 74 if data == "reuse": 75 print "用戶%s已登陸房間%s" %(username, room) 76 raw_input() 77 exit(1) 78 elif data == "success": 79 print "用戶%s成功登陸房間%s" %(username, room) 80 t = threading.Thread(target=Send, args = (chatCliSock, None)) 81 threads.append(t) 82 t = threading.Thread(target=Recieve, args = (chatCliSock, None)) 83 threads.append(t) 84 for i in range(len(threads)): 85 threads[i].start() 86 threads[0].join()