來源:DeveloperSSS 發(fā)布時間:2018-11-21 14:44:02 閱讀量:1326
服務端
#!/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類型數(shù)據(jù)
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)
#拼接返回數(shù)據(jù)
res_data = bytes(ctime(),encoding='utf-8')
#發(fā)送數(shù)據(jù)
conn.sendall(res_data)
#關(guān)閉連接
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('服務器返回內(nèi)容:'+str(accept_data, encoding="utf8"))
---------------------