tcp服务端和客户端

  • 服务端接受多个连接
# coding:utf-8

import socket

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
server.bind(('127.0.0.1',9002))
server.listen()
#while语句作用:(当客户端关闭后)接受新客户端的连接,实现服务端不间断地提供服务。
while True:
    conn,addr = server.accept()
    #while语句作用:接受来自客户端的消息、打印,回复消息;当客户端的消息中包含‘bye’时,断开本次连接。
    while True:
        msg = conn.recv(1024).decode('utf-8')
        print(msg)
        if 'bye' in msg:      #当收到的信息包含bye,给客户端发送bye,跳出当前while循环
            conn.send(b'bye')
            break
        info = "get it".encode('utf-8')
        conn.send(info)
conn.close()

server.close()
  • 客户端, 两个进程分别接受和发送,参考
from socket import *
import threading
tcp_socket = socket(AF_INET, SOCK_STREAM)
tcp_socket.connect(('127.0.0.1', 9002))
true = True


def rece_msg(tcp_socket):
 global true
 while true:
  recv_msg = tcp_socket.recv(1024).decode("utf8")
  if recv_msg == "exit":
   true = False
  print('接收到的信息为:%s\n' % recv_msg)


def send_msg(tcp_socket):
 global true
 while true:
  send_msg = input('请输入要发送的内容\n')
  tcp_socket.send(send_msg.encode('utf-8'))
  if send_msg == "exit":
   true = False


threading.Thread(target=send_msg, args=(tcp_socket,)).start()
threading.Thread(target=rece_msg, args=(tcp_socket,)).start()
import socket                        #网络编程需要用到socket模块

client = socket.socket()             #创建一个客户端
client.connect(('127.0.0.1', 9002))  #连接服务端

client.send(b'nice to meet you')     #向服务端发消息
s_info = client.recv(1024)           #接受服务端发来的消息
print(s_info)
client.close()                       #关闭客户端
  • 实现线程池多tcp服务端
from socket import *
import logging as logger
import concurrent.futures as futures
from multiprocessing.pool import ThreadPool

logger.basicConfig(level=logger.DEBUG)


class TCPServer:
    def __init__(self, host='127.0.0.1', port=9000):
        self.HOST = host
        self.PORT = port
        self.BUFSIZ = 1024
        self.ADDRESS = (self.HOST, self.PORT)
        self.clients = []
        self.pool = ThreadPool(processes=8)
        self.server_socket = socket() # AF_INET, SOCK_STREAM)
        self.server_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        self.server_socket.bind(self.ADDRESS)
        logger.info("服务器启动,监听端口{}...".format(self.ADDRESS))
        self.server_socket.listen(5)

    def launch(self):
        while True:
            print('服务器正在运行,等待客户端连接...')
            client_socket, client_address = self.server_socket.accept()

            self.pool.apply_async(self.func, args=(client_socket, client_address))
            print('{} 已连接!'.format(client_address))

    def func(self, client_socket, client_address):
        try:
            while True:
                data = client_socket.recv(self.BUFSIZ).decode("utf-8")
                if data:
                    print('接收到消息 {} ({} bytes) 来自 {}'.format(data, len(data), client_address))
                    client_socket.send(data.encode("utf-8"))
                else:
                    print("客户端{}已断开!".format(client_address))
                    self.clients.remove((client_socket, client_address))
                    break
        finally:
            client_socket.close()


def main():
    ts = TCPServer()
    ts.launch()


main()

客户端不变

你可能感兴趣的:(后端,tcp服务端)