python socket套接字网络编程通信服务端与客户端server_client_tcp

python socket套接字网络编程通信服务端与客户端

python socket套接字网络编程通信服务端与客户端server_client_tcp

 

服务端

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import socket

def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    s = socket.socket()
    host = socket.gethostname()
    port = 1666
    s.bind((host, port))
    s.listen(2)
    while True:
        c, addr = s.accept()
        print('获得连接from', addr)

        while True:
            data = c.recv(1024)
            #python38
            print("收到消息", data.decode())

          #c.send(encodings(return_str))
        #TypeError: a bytes-like object is required, not 'str',python3.8与2.7的区别
            # 这里使用python38
            c.send('收到回复'.encode())
            return_msg = "已回复"
            print("回复信息:", return_msg)

       # print(s.recv(1024))
       # c.send(bytes(port))
       # c.close()


    print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
 

 

客户端

import socket
HOST = '192.168.1.55'
PORT = 8001

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

while True:
    cmd = raw_input("Please input msg:")
    s.send(cmd)
    data = s.recv(1024)
    print data

    #s.close()

 

posted @ 2023-01-06 16:03  txwtech  阅读(27)  评论(0编辑  收藏  举报