栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python的socket多线程编程实现(附可实现源码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python的socket多线程编程实现(附可实现源码)

mySocket Introduction

Using python language to complete socket multi-threaded programming and pseudo-intelligent communication through dictionary set.

The following shows part of the source code.

Server.py

import socket
import threading
import time
import os

#字典集返回数据
def getAnswer(c_data):
    words = {'how are you?': 'Fine,thank you.',  # 字典集
             'hi': 'hello',
             'hello': 'hello',
             'how old are you?': '20',
             'what is your name?': 'Andel,
             "what's your name?": 'Andel',
             'where do you work?': 'Beijing',
             'bye': 'Bye'
             }
    flag = 0
    lst = list(words.keys())
    for i in range(len(lst)):
        if len(os.path.commonprefix([c_data, lst[i]])) > len(lst[i]) * 0.8:
            flag = 1
            return words.get(lst[i])
    if flag == 0:
        return "Sorry for that, I don't understand what you say."
#接收信息
def recv_msg(clientsocket,clientaddress):
    while True:
        recv_data = clientsocket.recvfrom(1024)
        ip,port = clientaddress
        print('Received from client('+ str(ip) + ':' + str(port) +'):'+ recv_data[0].decode())
        t_send = threading.Thread(target=send_msg, args=(clientsocket, clientaddress, recv_data[0]))
        t_send.start()
#发送信息
def send_msg(clientsocket,clientaddress, recv_data):
    ip,port = clientaddress
    time_data =  str(time.asctime(time.localtime()) + "n")
    ans_data = getAnswer(recv_data.decode())
    send_data = time_data + ans_data

    clientsocket.sendto(send_data.encode(),(ip,port))
#
def main():
    serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversocket.bind(('127.0.0.1', 8000))
    serversocket.listen(5)
    print('Server connecting....')
    while True:
        clientsocket, clientaddress = serversocket.accept()
        t_recv = threading.Thread(target=recv_msg, args=(clientsocket,clientaddress))
        t_recv.start()
        # print(str(len(threading.enumerate())) +  "threads are working")
        #
        # if (len(threading.enumerate())<2):
        #     break

    serversocket.close()

if __name__  == "__main__":
    main()

Client.py

import socket                     				                 #导入socket模块

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #创建客户机socket
clientsocket.connect(('127.0.0.1', 8000))                        #连接到服务器
while 1:                                                         #循环以接收用户输入,并发送到服务器,接收服务器的回送数据
    data = input('>')             				                 #接收用户输入数据
    clientsocket.send(data.encode()) 		                     #把数据转换为bytes对象,并发送到服务器
    if data=='exit': break             			                 #如果数据为exit,终止循环
    newdata = clientsocket.recv(1024) 	                         #接收服务器的回送数据
    print('Received from server: ',  newdata.decode() )          #输出接收到数据
clientsocket.close()                			                 #关闭客户机socket

Environment Configuration
  1. Python == 3.8
  2. Pycharm
Use Instruction
  1. Click directory “threadingsocket”
  2. Start the server first(server.py), Start the client1 and client2 then (client1.py + client2.py)
  3. Input in client
  4. Got response from server
Other Notes
  1. Open source code is for learning purposes only and cannot be used for other commercial purposes.
  2. The main function is to complete socket communication and multi-threaded tasks.
  3. Regarding smart chat, bloggers try to call other open source third-party libraries, such as Turing bots, but they are not allowed to be used for free testing right now. If you have a better way to achieve truly intelligent chat, feel free to contact me.
  4. Contact information: Andel2001@163.com
  5. Source code sharing link: https://gitee.com/andel/mySocket
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/499040.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号