TCP realizes network communication between two computers in different LAN (Python Implementation)

Posted by plimpton on Thu, 02 Apr 2020 16:24:44 +0200

Before, I have done the communication under the LAN. I found that I couldn't use the two computers on different LAN. I always want to realize something that can communicate in Wan! So there's this little project!

Implementation ideas:

Through a server with public IP as a transit station. Transfer the computer under the LAN to the transfer server, and then the transfer server will transfer the received data to another computer.

Technology concept

The following technologies are all for full duplex, and they also need to be more synchronous during transmission (network IO)

  • Server multithreaded, information received (divided into two threads)
  • The client realizes multithreading, receiving information and multithreading input at the same time.

Usage method

Run the server code on a server (on the public network). (what I use here is the server I rent in Alibaba cloud.)
Two people (in my case, only two people chat) run client code (or compiled client program (. exe format)) on their own computers.
Then, you can start chatting directly~
Enter a blank message to finish. (if one party ends, but the other party doesn't end, the other party can't receive ~ similar to sending information offline (although I don't set cache here...))

test result

The following is a case of receiving a remote information and sending a message. In fact, this is a full duplex chat tool, but I'm not good at this demonstration. I didn't show hhh, and these are hand built wheel HHS, which are very suitable for learning

[Sat Mar 3 23:52:23 2018] : Hello
what?

Code

Client code:

from socket import *
import threading
from time import ctime


def recv(sock, BUFSIZ):
    try:
        data = sock.recv(BUFSIZ)
    except OSError:
        return  # find it was close, then close it
    if data.decode() is '[CHAT]BEGIN':
        print(data.decode())
    elif data.decode() is '[CHAT]END':
        sock.close()
    else:
        print('[%s]' % ctime(), ':', data.decode())


if __name__ == '__main__':
    HOST = 'Public network of server IP address'
    POST = 21567
    ADDR = (HOST, POST)
    tcpCli = socket(AF_INET, SOCK_STREAM)

    tcpCli.connect(ADDR)

    threadrev = threading.Thread(target=recv, args=(tcpCli, 1024))
    threadrev.start()
    while True:
        data = input()
        if not data:
            break
        tcpCli.send(data.encode())
    tcpCli.close()

Server code ~ (running on a server)

from socket import *
import threading


def trans(sock1, sock2, BUFSIZ):
    while True:
        try:
            data = sock1.recv(BUFSIZ)
        except OSError:
            break
        if not data:
            sock1.close()
        else:
            try:
                sock2.send(data)
            except OSError:
                sock1.close()
                break


if __name__ == '__main__':
    HOST = ''
    POST = 21567
    ADDR = (HOST, POST)
    tcp = socket(AF_INET, SOCK_STREAM)
    tcp.bind(ADDR)
    tcp.listen(3)

    Users = []
    Addrs = []
    Trans = []
    while len(Users) != 2:
        tcpCli, addr = tcp.accept()
        Users.append(tcpCli)
    trans1 = threading.Thread(target=trans, args=(Users[0], Users[1], 1024))
    trans1.start()

    while True:
        try:
            data = Users[1].recv(1024)
        except OSError:
            break
        if not data:
            Users[1].close()
        else:
            try:
                Users[0].send(data)
            except OSError:
                Users[1].close()
                break
    tcp.close()

Topics: socket network