多线程GCD 队列 异步 网络 socket block 循环引用socketPython语言与信息数据获取和机器学习

多台机器通信的socket实现(Ubuntu16.04+pyth

2017-03-11  本文已影响625人  孙小雨
  1. 实验目的
    本文通过python实现了VMware下3台Ubuntu16.04虚拟机的通信,编写了一个一对多socket。

  2. 实验环境
    首先,VMware下的机器之间需要能够ping通,可以在VMware设置中将网络设置设为桥连。

  3. server端
    在设计一对多socket的server端时,有两个不同于一对一socket的点需要考虑:
    (1) 考虑到server端是一个广播源,可以连接无上限的client(当然你也可以自己设置一个上限flag),所以需要加入一个while循环,使server一直处于被连接状态;
    (2) 每多连接一个client,server就需要多开一个线程,用于处理新连接进来的client的请求;
    server段代码如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from socket import *
import threading
import time
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        print_time(self.name, self.counter, 3)
def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1
ClientConnected = 0 
threads = []
while 1:
    print 'waiting for connection...'
    tcpClisock,addr = tcpSerSock.accept()
    if 1:
        print '...connected from: ',addr
        ClientConnected += 1
        print 'Client: ',ClientConnected
        try:
            temp = myThread(ClientConnected, ClientConnected, 1)//线程函数可以根据需求自己扩展
            temp.start()
            threads.append(temp)
        except:
            print "error, thread"
print "Exiting Main Thread"
  1. client端
    client端设计比较简单,与一对一的socket没有什么不同,代码如下:
from socket import *

HOST = '192.168.3.217' //填写server端的ip地址
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = raw_input("Client>")
    if not data:
        break
//根据需求扩展功能函数

tcpCliSock.close()

附:运行
先在server上运行server.py,然后在每个client上运行client.py,效果如下:
server端:

Paste_Image.png

client端:

Paste_Image.png

测试成功,完。

上一篇下一篇

猜你喜欢

热点阅读