Python socket模拟聊天室(client)

网络编程这块应用的不多,今后多努力学习学习,但干啥都不能一口吃个胖子,往往最后瘦子也吃不了,还是从点滴做起,贵在坚持

今天浏览到一个socket实现的聊天室,挺有意思的,就转过来学习学习,做人要厚道,楼主都这么低调,怎么能窃取别人劳动果实呢,http://www.oschina.net/code/snippet_1387924_25928,有兴趣的可以自己传送去

这里脚本的运行不需要带任何参数,交互式地输入IP和用户名就行了,POST已经写死了,这些都是小事情,client脚本比较简单,启动两个线程,分别负责接收和输入信息,但是不能同时进行

client端:

#!/usr/bin/env python

import socket
import threading
 
inString = ”
outString = ”
nick = ”
 
def DealOut(s):
    global nick, outString
    while True:
        outString = raw_input()
        outString = nick + ‘: ‘ + outString
        s.send(outString)
 
def DealIn(s):
    global inString
    while True:
        try:
            inString = s.recv(1024)
            if not inString:
                break
            if outString != inString:
                print inString
        except:
            break
        
nick = raw_input(“input your nickname: “)
ip = raw_input(“input the server’s ip adrress: “)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, 8888))
sock.send(nick)
 
thin = threading.Thread(target = DealIn, args = (sock,))
thin.start()
thout = threading.Thread(target = DealOut, args = (sock,))
thout.start()

发表评论