Python实现TCP通讯

Environment

Client:Windows
Server:KaLi Linux(VM_virtul)
Network:Same LAN

Client

#!/usr/bin/python3
#-*- coding: utf-8 -*-
#@Time : 2021/3/26 23:22
#@Author : HUGBOY
#@File : TCPClient.py.py
#@Software: PyCharm

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#host = '192.168.1.xxx'
host = socket.gethostname()

port = 444

clientsocket.connect(('192.168.1.xxx', port))

message = clientsocket.recv(1024)

clientsocket.close()

print(message.decode('ascii'))

Server

#!/usr/bin/python3
#-*- coding: utf-8 -*-
#@Time : 2021/3/26 22:54
#@Author : HUGBOY
#@File : server.py.py
#@Software: PyCharm

import socket

#Creating the socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

#ip = '192.168.1.xxx'
#host = socket.gethostbyname()

host = '192.168.1.xxx'
port = 444

#Binding to socket
serversocket.bind((host, port))

#Starting TCP listener
serversocket.listen(3)

while True:
    #Staring the connection
    clientsocket, address = serversocket.accept()

    print("received connection from %s " % str(address))

    message = "Hello,I am TCPServer thanks to your connect."
    message = input('Reply:')

    clientsocket.send(message.encode('ascii'))

    clientsocket.close()

Effect

1.Client

2.Server

3.Client

posted @ 2021-03-27 19:36  HUGBOY  阅读(485)  评论(0编辑  收藏  举报