本文为大家分享了Python多线程聊天室,是一个Socket,两个线程,一个是服务器,一个是客户端。
最近公司培训,要写个大富翁的小程序,准备做个服务器版的,先练练手。
代码:
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
|
#coding = utf-8
import socket
import threading
class UdpServer(threading.Thread):
def __init__( self ):
threading.Thread.__init__( self )
self .address = ( '127.0.0.1' , 10000 )
self .s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self .s.bind( self .address)
self .stop_flag = False
def recieve_msg( self ):
(data, addr) = self .s.recvfrom( 2048 )
if data:
print 'recieve data from' , addr
print data
def run( self ):
while not self .stop_flag:
self .recieve_msg()
def stop( self ):
self .stop_flag = True
class UdpClient(threading.Thread):
def __init__( self ):
threading.Thread.__init__( self )
self .address = ( '127.0.0.1' , 10001 )
self .s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self .stop_flag = False
def send_msg( self ):
data = raw_input ()
if not data:
print 'Wrong inpiut'
return
else :
self .s.sendto(data, self .address)
def run( self ):
while not True :
self .send_msg()
def stop( self ):
self .stop_flag = True
def main():
t1 = UdpServer()
t2 = UdpClient()
t1.start()
t2.start()
if __name__ = = '__main__' :
main()
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u012225151/article/details/52260835