python tcp server-client
基本思路:
1、指定IP、端口号;
2、绑定;
3、开启监听;
4、接受连接创建socket;
5、收发数据
参考来源 python tcp server 连接多个客户端
tcp_server
# tcp_server
# coding=utf-8
# !/usr/bin/env python
import socket
import time
import threading
serverIP = "0.0.0.0"
serverPort = 10620
clientSocketList = [] # 放每个客户端的socket
def init_server():
sockServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sockServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_addr = (serverIP, serverPort)
sockServer.bind(server_addr)
sockServer.listen(10)
print(server_addr)
print("The server has started, waiting for the client to connect ......")
return sockServer
def accept_client(sockServer):
while True:
time.sleep(0.1)
clientSock, addr = sockServer.accept()
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strPrint = 'connected from: {}'.format(addr)
strPrint = strTime + strPrint
print(strPrint)
clientSock.setblocking(0)
clientSocketList.append([clientSock, addr])
def server_Send(direction):
while True:
time.sleep(0.1)
try:
sendByte = bytes(direction)
for clientInfo in clientSocketList:
currClient, addr = clientInfo
currClient.sendall(sendByte)
print("to {}, send <{}> ".format(addr, sendByte))
except Exception as e:
clientSocketList.remove(clientInfo)
continue
def server_Recv():
while True:
time.sleep(0.1)
for clientInfo in clientSocketList:
# print(client.getsockname())
# print(client.getpeername())
currClient, addr = clientInfo
try:
dataRecv = currClient.recv(1024)
except Exception as e:
continue
if not dataRecv:
clientSocketList.remove(clientInfo)
print("currClient{} has closeed.\n".format(addr))
continue
try:
direction = float(dataRecv)
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strRecv = "from {} recv len={}, data={}".format(addr, len(dataRecv), direction)
print(strRecv)
except Exception as e:
print(e)
pass
if __name__ == '__main__':
sockServer = init_server()
threadCheckClient = threading.Thread(target=accept_client, args=(sockServer, )) # 子线程
# threadCheckClient.setDaemon(True)
threadCheckClient.start()
threadSend = threading.Thread(target=server_Recv) # 子线程
# threadSend.setDaemon(True)
threadSend.start()
tcp_client
# tcp_client
# coding=utf-8
# !/usr/bin/env python
import socket
import sys, time
from threading import Thread
serverIP = '127.0.0.1'
serverPort = 10620
def init_client():
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp_client.connect((serverIP, serverPort))
except socket.error:
print('fail to setup socket connection')
return tcp_client
def client_Send(tcp_client):
while True:
time.sleep(0.1)
time.sleep(1)
try:
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strTime = str(12345.5678909)
sendBytes =strTime.encode()
tcp_client.sendall(sendBytes)
print(sendBytes)
except Exception as e:
break
def client_Recv(tcp_client):
while True:
time.sleep(0.1)
try:
dataRecv = tcp_client.recv(1024) # 到这里程序继续向下执行
except Exception as e:
continue
if not dataRecv:
break
else:
strTime = time.strftime('%Y-%m-%d %H:%M:%S')
strRecv = "from server recv len={}, data={}".format( len(dataRecv), dataRecv)
strPrint = strTime + strRecv
print(strPrint)
if __name__ == "__main__":
tcp_client = init_client()
threadSend = Thread(target=client_Send, args=(tcp_client, )) # 子线程
threadSend.start()