相对于java方式的聊天室,python同样可以做得到。而且可以做的更加的优雅。想必少了那么多的各种流的python socket,你一定会喜欢的。
至于知识点相关的内容,这里就不多说了。
udp方式
服务器端
# coding:utf-8
# __author__ = ‘mark sinoberg’
# __date__ = ‘2016/7/7’
# __desc__ = 创建一个简单的套接字监听请求
import socket
host = ‘192.168.59.255’
port = 9998
s = socket.socket(socket.af_inet,socket.sock_dgram)
s.bind((”,port))
print ‘套接字已启动!’
while true:
data,addr = s.recvfrom(1024)
print addr,str(‘ : ‘)+data
客户端
# coding:utf-8
# __author__ = ‘mark sinoberg’
# __date__ = ‘2016/7/7’
# __desc__ = socket的客户端的简单实现
import socket
port = 9998
host = ‘192.168.59.255’
s = socket.socket(socket.af_inet,socket.sock_dgram)
words = raw_input(‘client:’)
while words != ‘quit’:
s.sendto(words,(host,port))
words = raw_input(‘client:’)
s.close()
是不是很简单啊。我们需要注意的就是socket的第二个参数为sock_dgram。因为这和tcp方式的sock_stream 有所不同。
tcp方式
服务器端
# coding:utf-8
# __author__ = ‘mark sinoberg’
# __date__ = ‘2016/7/7’
# __desc__ = 简单的tcpsocket的实现
from socket import *
from time import ctime
host = ”
port = 9999
buffersize = 1024
address = (host,port)
s = socket(af_inet,sock_stream)
s.bind(address)
s.listen(5)
while true:
print ‘waiting for clients cennect!’
tcpclient,addr = s.accept()
print ‘connected by ‘,addr
while true:
try:
data = tcpclient.recv(buffersize)
except exception,e:
print e.message
tcpclient.close()
break
if not data:
print “no data received!”
break
senddata = ‘hi,you send me:[%s]%s’%(ctime(),data.encode(‘utf8’))
tcpclient.send(senddata.encode(‘utf8′))
print addr,’ says:’,ctime(),data.encode(‘utf8’)
tcpclient.close()
s.close()
客户端
# coding:utf-8
# __author__ = ‘mark sinoberg’
# __date__ = ‘2016/7/7’
# __desc__ = 简单的tcp socket客户端的实现
from socket import *
class tcpclient:
# 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))
while true:
senddata = raw_input(‘>>>’)
if not senddata:
print ‘please input some words!\n>>>’
continue
if senddata == “quit”:
break
self.client.send(senddata.encode(‘utf8’))
recvdata = self.client.recv(self.buffsiz)
if not recvdata:
break
print recvdata.encode(‘utf8’)
if __name__ == “__main__”:
client = tcpclient()
tcp方式演示结果:(注意先开启服务器端)
服务器端
d:\software\python2\python.exe e:/code/python/mytestset/sockettest/simpletcpserver.pywaiting for clients cennect!connected by (‘192.168.59.225’, 63095)(‘192.168.59.225’, 63095) says: thu jul 07 16:01:10 2016 hello world(‘192.168.59.225’, 63095) says: thu jul 07 16:01:15 2016 haode no data received!waiting for clients cennect!
客户端
d:\software\python2\python.exe e:/code/python/mytestset/sockettest/simpletcpclient.py>>>hello worldhi,you send me:[thu jul 07 16:01:10 2016]hello world>>>please input some words!>>>>>>haode hi,you send me:[thu jul 07 16:01:15 2016]haode >>>quit
process finished with exit code 0
总结
简单的使用tcp或者是udp确实很容易,然而要想更好的利用这两个协议,就需要好好的设计一番了。
这里我想强调的是,注意tcp和udp创建套接字时指定的参数即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持php中文网。
更多聊天室python代码实现相关文章请关注php中文网!