TCPClient
from socket import *
def clientmain():
#主机地址
IP='192.168.59.1'
SERVER_PORT=8000
BUFLEN=1024
#实例化对象
dataSocket=socket(AF_INET,SOCK_STREAM)
dataSocket.connect((IP,SERVER_PORT))
while True:
toSend="send"
dataSocket.send(toSend.encode('utf8'))
recved=dataSocket.recv(BUFLEN)
if not recved:
break
print(recved.decode())
dataSocket.close()
if __name__ == "__main__":
clientmain()
TCPServer
from socket import *
def servermain():
#主机地址
IP='192.168.118.1'
PORT=5000
BUFLEN = 512
#实例化对象
listenSocket=socket(AF_INET,SOCK_STREAM)
listenSocket.bind((IP,PORT))
listenSocket.listen(5)
print(f'服务启动成功,在{PORT}端口等待客户端连接...')
dataSocket,addr=listenSocket.accept()
print('接收客户端连接:',addr)
while True:
recved=dataSocket.recv(BUFLEN)
if not recved:
break
info=recved.decode()
print('接收到对方信息:{info}')
dataSocket.send(f'接收到对方信息:{info}'.encode('utf8'))
dataSocket.close()
listenSocket.close()
if __name__ == "__main__":
servermain()
?
|