使用python套接字发送/接收数据

时间:2017-02-23 12:01:32

标签: python sockets vpn data-transfer

我有一个vpn(使用OpenVPN),多个客户端连接到服务器(在DigitalOcean)。连接非常好,当他们通过ssh连接到各自的路由器时,我能够访问各自防火墙后面的每个客户端。我想使用python脚本自动将文件从多个客户端发送到服务器,反之亦然。这是我到目前为止使用的代码:

服务器:

#!/usr/bin/env python

import socket
from threading import Thread
from SocketServer import ThreadingMixIn

class ClientThread(Thread):

    def __init__(self,ip,port):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        print "[+] New thread started for "+ip+":"+str(port)


    def run(self):
        while True:
            data = conn.recv(2048)
            if not data: break
            print "received data:", data
            conn.send(data)  # echo

TCP_IP = '0.0.0.0'
TCP_PORT = 62
BUFFER_SIZE = 1024  # Normally 1024


tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []

while True:
    tcpsock.listen(4)
    print "Waiting for incoming connections..."
    (conn, (ip,port)) = tcpsock.accept()
    newthread = ClientThread(ip,port)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()

客户端:

#!/usr/bin/env python

import socket


TCP_IP = '10.8.0.1'
TCP_PORT = 62

BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

print "received data:", data

问题是我无法获得连接。服务器只打印“等待传入连接...”,客户端似乎没有找到通往服务器的路径。是否有人可以看一下这个并给我一些反馈,我做错了?

1 个答案:

答案 0 :(得分:3)

你能尝试这样的事吗?

import socket
from threading import Thread


class ClientThread(Thread):

    def __init__(self,ip,port):
    Thread.__init__(self)
    self.ip = ip
    self.port = port
    print "[+] New thread started for "+ip+":"+str(port)


def run(self):
    while True:
        data = conn.recv(2048)
        if not data: break
        print "received data:", data
        conn.send("<Server> Got your data. Send some more\n")

TCP_IP = '0.0.0.0'
TCP_PORT = 62
BUFFER_SIZE = 1024  # Normally 1024
threads = []

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("0.0.0.0", 5000))
server_socket.listen(10)

read_sockets, write_sockets, error_sockets = select.select([server_socket], [], [])

while True:
    print "Waiting for incoming connections..."
    for sock in read_sockets:
        (conn, (ip,port)) = server_socket.accept()
        newthread = ClientThread(ip,port)
        newthread.start()
        threads.append(newthread)

for t in threads:
    t.join()

现在客户端将具有以下内容:

import socket, select, sys

TCP_IP = '0.0.0.0'
TCP_PORT = 62

BUFFER_SIZE = 1024
MESSAGE = "Hello, Server. Are you ready?\n"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, 5000))
s.send(MESSAGE)
socket_list = [sys.stdin, s]

while 1:
    read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])


    for sock in read_sockets:
        # incoming message from remote server
        if sock == s:
            data = sock.recv(4096)
            if not data:
                print('\nDisconnected from server')
                sys.exit()
            else:
                sys.stdout.write("\n")
                message = data.decode()
                sys.stdout.write(message)
                sys.stdout.write('<Me> ')
                sys.stdout.flush()

        else:
            msg = sys.stdin.readline()
            s.send(bytes(msg))
            sys.stdout.write('<Me> ')
            sys.stdout.flush()

输出如下:

对于服务器 -

Waiting for incoming connections...
[+] New thread started for 127.0.0.1:52661
received data: Hello, World!
Waiting for incoming connections...

received data: Hi!

received data: How are you?

对于客户 -

<Server> Got your data. Send some more
<Me> Hi!
<Me> 
<Server> Got your data. Send some more
<Me> How are you?
<Me> 
<Server> Got your data. Send me more
<Me>

如果您希望在客户端和服务器之间建立开放连接,只需在无限循环中保持客户端打开,您也可以在服务器端进行一些消息处理。如果您需要,我可以相应地编辑答案。希望这会有所帮助。