相对于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:SoftwarePython2python.exe E:/Code/Python/MyTestSet/sockettest/SimpleTCPServer.py
Waiting 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:SoftwarePython2python.exe E:/Code/Python/MyTestSet/sockettest/SimpleTcpClient.py
>>>Hello World
Hi,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创建套接字时指定的参数即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。