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
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值