Python3服务端与客户端实现

来源:DeveloperSSS 发布时间:2018-11-21 14:44:02 阅读量:1324

服务端


#!/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()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

客户端


#!/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"))

--------------------- 



标签: 服务器搭建
分享:
评论:
你还没有登录,请先