Python Socket编程之多线程聊天室

yipeiwu_com7年前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设计】。

相关文章

python os.path.isfile 的使用误区详解

下列这几条语句,看出什么问题了不? for file in os.listdir(path): if os.path.isfile(file) and os.path.spl...

教你用Type Hint提高Python程序开发效率

简介 Type Hint(或者叫做PEP-484)提供了一种针对Python程序的类型标注标准。 为什么使用Type Hint?对于动态语言而言,常常出现的情况是当你写了一段代码后,隔段...

Python httplib,smtplib使用方法

例一:使用httplib访问某个url然后获取返回的内容:import httplib conn=httplib.HTTPConnection("www.ting...

ansible作为python模块库使用的方法实例

前言 ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet、cfengine、chef、func、fabric)的优点,实现了批量系统配置、批量...

为什么Python中没有"a++"这种写法

一开始学习 Python 的时候习惯性的使用 C 中的 a++ 这种写法,发现会报 SyntaxError: invalid syntax 错误,为什么 Python 没有自增运算符的这...