简体   繁体   English

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

[英]Send/receive data with python socket

I have a vpn (using OpenVPN) with mulitple clients connected to a server (at DigitalOcean).我有一个 vpn(使用 OpenVPN),其中有多个客户端连接到服务器(在 DigitalOcean)。 The connection is very good and I am able access every client placed behind their respective firewalls when they are connected to their respective routers through ssh.连接非常好,当它们通过 ssh 连接到各自的路由器时,我能够访问位于各自防火墙后面的每个客户端。 I want to use python scripts to automatically send files from multiple clients to server and vice versa.我想使用 python 脚本自动将文件从多个客户端发送到服务器,反之亦然。 Here's the code I am using so far:这是我目前使用的代码:

Server:服务器:

#!/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()

Client:客户:

#!/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

The problem is im not able to get a connection.问题是我无法获得连接。 The server only prints "Waiting for incoming connections..." and the client does not seem to find its way to the server.服务器只打印“等待传入连接...”,客户端似乎没有找到通往服务器的路。 Is there anyone who can take a look at this and give me some feedback on wath I am doing wrong?有没有人可以看看这个并给我一些关于我做错了什么的反馈?

Can you try something like this?你能试试这样的吗?

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(b"<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()

Now the client will have something like below:现在客户端将有如下内容:

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()

The output is as below:输出如下:

For server -对于服务器 -

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?

For client -对于客户 -

<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>

In case you want to have an open connection between the client and server, just keep the client open in an infinite while loop and you can have some message handling at the server end as well.如果您想在客户端和服务器之间建立一个开放的连接,只需在无限的 while 循环中保持客户端打开,您也可以在服务器端进行一些消息处理。 If you need that I can edit the answer accordingly.如果您需要,我可以相应地编辑答案。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM