hello大家好,今天说一下python的socket编程,基于python的socket通信的文本框网络聊天
首先,实验环境:
一个云服务器(我们这里是用的阿里云,大家将就自己的条件吧);
类unix操作系统(如mac os,linux等);
windows系列操作系统。
在这里,我使用的是阿里云,mac osx,windows xp(在mac上的一个虚拟机)。
server.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
# -*- coding: utf-8 -*- #!/usr/local/bin/python import socket import sys import 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
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
# -*- coding: utf-8 -*- import socket import threading import 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通信的文本框网络聊天室就写好了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/KarlDoenitz/article/details/23297191