小小聊天室Python代码实现
相对于Java方式的聊天室,Python同样可以做得到。而且可以做的更加的优雅。想必少了那么多的各种流的PythonSocket,你一定会喜欢的。
至于知识点相关的内容,这里就不多说了。
UDP方式
服务器端
#coding:utf-8 #__author__='Marksinoberg' #__date__='2016/7/7' #__Desc__=创建一个简单的套接字监听请求 importsocket HOST='192.168.59.255' PORT=9998 s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(('',PORT)) print'套接字已启动!' whileTrue: data,addr=s.recvfrom(1024) printaddr,str(':')+data
客户端
#coding:utf-8 #__author__='Marksinoberg' #__date__='2016/7/7' #__Desc__=socket的客户端的简单实现 importsocket PORT=9998 HOST='192.168.59.255' s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) words=raw_input('Client:') whilewords!='quit': s.sendto(words,(HOST,PORT)) words=raw_input('Client:') s.close()
是不是很简单啊。我们需要注意的就是socket的第二个参数为SOCK_DGRAM。因为这和TCP方式的SOCK_STREAM有所不同。
TCP方式
服务器端
#coding:utf-8 #__author__='Marksinoberg' #__date__='2016/7/7' #__Desc__=简单的tcpsocket的实现 fromsocketimport* fromtimeimportctime HOST='' PORT=9999 BUFFERSIZE=1024 ADDRESS=(HOST,PORT) s=socket(AF_INET,SOCK_STREAM) s.bind(ADDRESS) s.listen(5) whileTrue: print'Waitingforclientscennect!' tcpclient,addr=s.accept() print'ConnectedBy',addr whileTrue: try: data=tcpclient.recv(BUFFERSIZE) exceptException,e: printe.message tcpclient.close() break ifnotdata: print"NoDatareceived!" break senddata='Hi,yousendme:[%s]%s'%(ctime(),data.encode('utf8')) tcpclient.send(senddata.encode('utf8')) printaddr,'Says:',ctime(),data.encode('utf8') tcpclient.close() s.close()
客户端
#coding:utf-8 #__author__='Marksinoberg' #__date__='2016/7/7' #__Desc__=简单的tcpsocket客户端的实现 fromsocketimport* classTcpClient: #HOST='localhost' PORT=9999 HOST='192.168.59.225' BUFFSIZ=1024 ADDR=(HOST,PORT) def__init__(self): self.client=socket(AF_INET,SOCK_STREAM) self.client.connect((self.HOST,self.PORT)) whileTrue: senddata=raw_input('>>>') ifnotsenddata: print'Pleaseinputsomewords!\n>>>' continue ifsenddata=="quit": break self.client.send(senddata.encode('utf8')) recvdata=self.client.recv(self.BUFFSIZ) ifnotrecvdata: break printrecvdata.encode('utf8') if__name__=="__main__": client=TcpClient()
TCP方式演示结果:(注意先开启服务器端)
服务器端
D:\Software\Python2\python.exeE:/Code/Python/MyTestSet/sockettest/SimpleTCPServer.py
Waitingforclientscennect!
ConnectedBy ('192.168.59.225',63095)
('192.168.59.225',63095) Says:ThuJul0716:01:102016HelloWorld
('192.168.59.225',63095) Says:ThuJul0716:01:152016haode
NoDatareceived!
Waitingforclientscennect!
客户端
D:\Software\Python2\python.exeE:/Code/Python/MyTestSet/sockettest/SimpleTcpClient.py
>>>HelloWorld
Hi,yousendme:[ThuJul0716:01:102016]HelloWorld
>>>
Pleaseinputsomewords!
>>>
>>>haode
Hi,yousendme:[ThuJul0716:01:152016]haode
>>>quit
Processfinishedwithexitcode0
总结
简单的使用TCP或者是UDP确实很容易,然而要想更好的利用这两个协议,就需要好好的设计一番了。
这里我想强调的是,注意tcp和udp创建套接字时指定的参数即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。