1、服務(wù)器采用socket模塊,以命令行窗口運(yùn)行,核心代碼如下
while True:
count = 0
print 'Waiting for connection...'
tcpCliSock, addr = tcpSerSock.accept()
print '...connection from:', addr
while count <= len(chatdata):
i = 1
data = tcpCliSock.recv(BUFSIZ)
if data == 'quit':
break
if count == len(chatdata):
break
for t in chatdata[count]:
tcpCliSock.send(t.strip())
i += 1
print 'Function send call count:', i
count += 1
tcpCliSock.close()
chatdata為創(chuàng)建的回復(fù)信息列表,接收到客戶端的連接后不斷向客戶端發(fā)消息,回復(fù)信息被分割成單字符,并將send函數(shù)調(diào)用次數(shù)信息顯示在服務(wù)器端。
2.客戶端采用對(duì)話框界面(pyqt4 designer設(shè)計(jì))

主界面
def Send(self):
data = self.textEdit.toPlainText()
if not data:
msgbox = QMessageBox.information(u'Attention','Please don\'t input valid message!!',QMessageBox.Ok)
else:
self.textBrowser.append('you:'+ data)
tcpCliSock.send(data)
self.textEdit.clear()
def Receive(self):
while True:
time.sleep(0.5)
result = tcpCliSock.recv(BUFSIZ)
self.textBrowser.append('clearlove7:'+result)
此Send函數(shù)為確認(rèn)發(fā)送按鈕的事件函數(shù),Receive 采用多線程接受服務(wù)器端的信息。

客戶端端口信息
總結(jié)
本次作業(yè)涉及到的知識(shí)點(diǎn)較多,不僅要讀懂Tcp/Ip網(wǎng)絡(luò)編程中的內(nèi)容,還要清楚socket套接字在python中的具體實(shí)現(xiàn),關(guān)鍵在于對(duì)TCP流套接字 “順序可靠的、不重復(fù)傳輸、無(wú)數(shù)據(jù)邊界”的通信方式的理解。還有一個(gè)容易忽略的就是端口的設(shè)置,不能重復(fù),主機(jī)名的設(shè)置也要完全一樣。