Hello大家好,今天说一下python的socket编程,基于python的socket通信的文本框网络聊天
首先,实验环境:
一个云服务器(我们这里是用的阿里云,大家将就自己的条件吧);
类Unix操作系统(如Mac OS,Linux等);
Windows系列操作系统。
在这里,我使用的是阿里云,Mac OSX,Windows XP(在mac上的一个虚拟机)。
Server.py
# -*- coding: utf-8 -*-#!/usr/local/bin/python import socketimport sysimport threading con = threading.Condition()HOST = "云空间的IP地址"PORT = 端口 data = '' s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)print 'Socket created's.bind((HOST, PORT))s.listen(10)print 'Socket now listening' def clientThreadIn(conn, nick):#开辟线程 global data while True:#接受客户端数据 try: temp = conn.recv(1024) if not temp: conn.close()#连接关闭 return NotifyAll(temp) print data except: NotifyAll(nick + " leaves the room!") print data return def NotifyAll(sss):#广播 global data if con.acquire(): data = sss con.notifyAll() con.release() def ClientThreadOut(conn, nick):#客户端输出 global data while True: if con.acquire(): con.wait() if data: try: conn.send(data) con.release() except: con.release() return while 1: conn, addr = s.accept() print 'Connected with ' + addr[0] + ':' + str(addr[1]) nick = conn.recv(1024) NotifyAll('Welcome ' + nick + ' to the room!') print data print str((threading.activeCount() + 1) / 2) + ' person(s)!' conn.send(data) threading.Thread(target = clientThreadIn , args = (conn, nick)).start()#开辟线程 threading.Thread(target = ClientThreadOut , args = (conn, nick)).start() s.close()
Client.py
# -*- coding: utf-8 -*- import socketimport threadingimport getpass inString = ''outString = ''nick = '' def DealOut(s): computername=socket.gethostname()#获取计算机名 global nick, outString while True: outString = raw_input(nick+":") outString = nick + "@" + computername + ': ' + 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 = getpass.getuser()#获取操作系统用户名ip = "云空间IP地址"sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)sock.connect((ip, 端口))sock.send(nick) thin = threading.Thread(target = DealIn, args = (sock,))#开辟一个读入的线程thin.start()thout = threading.Thread(target = DealOut, args = (sock,))#开辟一个写出的线程thout.start()
将server.py上传云端,运行,如图:
将client.py在mac系统上运行,如图:
将client.py在WindowsXP虚拟机上运行,如图:
OK,这就可以了,一个基于python的socket通信的文本框网络聊天室就写好了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。
注:相关教程知识阅读请移步到python教程频道。