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

相关文章

pytorch实现focal loss的两种方式小结

我就废话不多说了,直接上代码吧! import torch import torch.nn.functional as F import numpy as np from torch...

Python读写txt文本文件的操作方法全解析

Python读写txt文本文件的操作方法全解析

一、文件的打开和创建 >>> f = open('/tmp/test.txt') >>> f.read() 'hello python!\nhel...

python实现K近邻回归,采用等权重和不等权重的方法

如下所示: from sklearn.datasets import load_boston boston = load_boston() from sklearn.cros...

Python下的Softmax回归函数的实现方法(推荐)

Python下的Softmax回归函数的实现方法(推荐)

Softmax回归函数是用于将分类结果归一化。但它不同于一般的按照比例归一化的方法,它通过对数变换来进行归一化,这样实现了较大的值在归一化过程中收益更多的情况。 Softmax公式 S...

python3 selenium自动化测试 强大的CSS定位方法

ccs的优点:css相对xpath语法比xpath简洁,定位速度比xpath快 css的缺点:css不支持用逻辑运算符来定位,而xpath支持。css定位语法形式多样,相对xpath比较...