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

相关文章

解决python报错MemoryError的问题

如下: python 32bit 最大只能使用 2G 内存,坑爹之处,超过 2G 报错MemoryError。 而 64bit python则无此限制,所以建议使用 64bit pyth...

python利用7z批量解压rar的实现

一开始我使用了rarfile这个库,奈何对于含有密码的压缩包支持不好,在linux上不抛出异常;之后有又尝试了unrar。。比rarfile还费劲。。 所以用了调用系统命令的方法,用7z...

详解python while 函数及while和for的区别

详解python while 函数及while和for的区别

1.while循环(只有在条件表达式成立的时候才会进入while循环) while 条件表达式:   pass while 条件表达式:   pass else:   pass 不知道...

Django models.py应用实现过程详解

Django models.py应用实现过程详解

编写 models.py 文件 from django.db import models # Create your models here. class User_info(mod...

Python入门学习指南分享

Python入门学习指南分享

对于初学者,入门至关重要,这关系到初学者是从入门到精通还是从入门到放弃。以下是结合Python的学习经验,整理出的一条学习路径,主要有四个阶段 NO.1 新手入门阶段,学习基础知识 总体...