首页 > 代码库 > python socket之编写一个类QQ通信工具

python socket之编写一个类QQ通信工具

       今天刚写完ssh程序,感觉跟写一个QQ及时通信的原理差不多,所以就利用下午的时间进行修改一下早上得代码,ssh里面有个bug就是当客户端或者服务端没有输入直接按回车的时候进程就死掉。这里就加个简单的循环判断而已。其他的原理都一样:

服务端代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import os
import time
HOST = ‘‘
PORT = 11111
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((HOST,PORT))
s.listen(2)
conn,addr = s.accept()

#########-----------------
#print ‘Got client from:‘,addr
while True:
        data = http://www.mamicode.com/conn.recv(4096)
        print addr,‘ say:\n‘,data
        if not data:
                time.sleep(1.5)
        cmd=raw_input(":")
        if len(cmd)==0:
                print "please input something:"
                continue
        else:
                pass
        conn.sendall(cmd)
conn.close()

 

客户端代码:

#/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
from time import sleep
h = ‘192.168.63.129‘
p = 11111
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((h,p))
print "connect to %s ,please input commend:\n" %(h)
while True:
#       print "from %s say:" %(h)
        INPUT = raw_input(":")
        if len(INPUT) ==0:
                print "your must input your command:"
                continue
        if INPUT == exit:
                break
        s.send(INPUT)
        received_data = http://www.mamicode.com/s.recv(1024)
        print "from %s say:\n" %(h),received_data
        sleep(1)
s.close()

 

显示效果如下:

服务器端:

技术分享

客户端效果如下:

技术分享

 

 

本文出自 “小罗” 博客,请务必保留此出处http://xiaoluoge.blog.51cto.com/9141967/1591740

python socket之编写一个类QQ通信工具