Python Socket编程之多线程聊天室

yipeiwu_com6年前Python基础

本文为大家分享了Python多线程聊天室,是一个Socket,两个线程,一个是服务器,一个是客户端。
最近公司培训,要写个大富翁的小程序,准备做个服务器版的,先练练手。

代码:

#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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

30秒轻松实现TensorFlow物体检测

Google发布了新的TensorFlow物体检测API,包含了预训练模型,一个发布模型的jupyter notebook,一些可用于使用自己数据集对模型进行重新训练的有用脚本。 使用该...

使用Python的Twisted框架编写简单的网络客户端

Protocol   和服务器一样,也是通过该类来实现。先看一个简短的例程: from twisted.internet.protocol import Protocol...

Django URL传递参数的方法总结

1 无参数情况 配置URL及其视图如下: (r'^hello/$', hello) def hello(request): return HttpResponse("Hell...

元组列表字典(莫烦python基础)

Tuple 叫做 tuple,用小括号、或者无括号来表述,是一连串有顺序的数字。 a_tuple = (12, 3, 5, 15 , 6) another_tuple = 12,...

Python简直是万能的,这5大主要用途你一定要知道!(推荐)

从2015开始国内就开始慢慢接触Python了,从16年开始Python就已经在国内的热度更高了,目前也可以算的上"全民Python"了。 众所周知小学生的教材里面已经有Python了,...