服务端

#!/usr/bin/python
# -*- coding:utf-8 -*-
import socket
from socket import *
from time import ctime

tcpSocket = socket(AF_INET,SOCK_STREAM)
# udpSocket = socket(AF_INET,SOCK_DGRAM)
tcpSocket.bind(('127.0.0.1',8888 ))
tcpSocket.listen(5)

while True:
    #等待客户端连接
    conn ,addr = tcpSocket.accept()
    #接收到byte类型数据
    while True:
        accept_data = conn.recv(1024)
        if not accept_data:
            break

        accept_data_str = str(accept_data,encoding='utf-8')
        print(accept_data_str)

        #拼接返回数据
        res_data = bytes(ctime(),encoding='utf-8')

        #发送数据
        conn.sendall(res_data)
    #关闭连接
    conn.close()

tcpSocket.close()

客户端

#!/usr/bin/python
# -*- coding:utf-8 -*-

from socket import *

HOST = '127.0.0.1'
PORT = 8888
BUFFSIZE = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR) # 主动初始化与服务器端的连接

while True:
    send_data = input("> ")
    tcpCliSock.sendall(bytes(send_data, encoding="utf8"))
    accept_data = tcpCliSock.recv(1024)
    print('服务器返回内容:'+str(accept_data, encoding="utf8"))
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐