python socket聊天小工具

Server端代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#coding=gbk
from socket import *
import time
import threading
def answer_screen(HOST,PORT,BUFSIZE):
    ADDR = (HOST,PORT)
    tcpsersock =socket(AF_INET,SOCK_STREAM)
    tcpsersock.bind(ADDR)
    tcpsersock.listen(5)
               
    while True:
        print '正在連接...............................'
        tcpconnection,addr=tcpsersock.accept()
        print '連接從:',addr
                   
        while True:
            data = tcpconnection.recv(BUFSIZE)
            if not data:
                break
            tcpconnection.send('[%s] %s' % (time.ctime(),data))
            print [time.ctime()],':',data
                   
    tcpconnection.close()
    tcpsersock.close()
               
if __name__ == '__main__':
    answer_screen('127.0.0.1',21567,1024)



Clinet代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#conding=gbk
from socket import *
def  answer_client(HOST,PORT,BUFSIZE):
    ADDR = (HOST,PORT)
    tcpconnection = socket(AF_INET,SOCK_STREAM)
    tcpconnection.connect(ADDR)
       
    while True:
        data =raw_input('>')
        if not data:
            break
        tcpconnection.send(data)
        data = tcpconnection.recv(BUFSIZE)
        if not data:
            break
        print data
    tcpconnection.close()
if __name__ == '__main__':
    answer_client('127.0.0.1',21567,1024)

轉自:http://brotherxing.blog.51cto.com/blog/3994225/1317449
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章