繁体   English   中英

套接字不与其他网络通信

[英]Socket doesn't communicate with other networks

我试图从一台计算机向另一台计算机发送一个 8 位密码,当两台计算机在同一个网络上时,该代码有效。但是当它们不在同一个网络上时似乎有问题。 它只是不将 pin 发送到服务器 pc。

从客户端接收数据并保存 server.py

import socket
import json
import Classes


def recive_pin(s_data):
    pin = s_data.recv(int(s_data.recv(1).decode())).decode()
    return pin


def main():
    # gets port from json file
    with open("Config.JSON", 'r') as f:
        json_data = json.load(f)
        port = json_data["load"]["port"]
    # create the tcp socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # binds the socket to localhost , config port number
    ip = '0.0.0.0'
    s.bind((ip, port))
    user_data = {}
    while 1:
        s.listen()
        s_data, address = s.accept()
        command = s_data.recv(1).decode()
        if command == "P":
            user_data[recive_pin(s_data)] = address
            print(user_data)


if __name__ == '__main__':
    main()

client.py 创建一个 8 位代码并将其发送到服务器

import socket
import json

import Classes


def main():
    # gets the user input controlled/controller.


    with open("Config.JSON", 'r') as f:
        json_data = json.load(f)
        port = json_data["load"]["port"]
        ip = json_data["load"]["ip"]

    c = Classes.handler(ip, port)
    x = Classes.pin.create_pin()

    c.send_pin(x)


if __name__ == '__main__':
    main()

类.py

import random
import string
import socket


class handler:
    def __init__(self, comunication_ip=0, port=0, ):
        self.__comunication_ip = comunication_ip
        self.__port = int(port)

        # type of command to send to the server

        # tuple of the server details
        self.__server_details = (self.__comunication_ip, self.__port)

    def send_pin(self, verification_pin):
        # command type : Send_pin("P")
        command_type = "P"
        # creates a socket to send the pin to the server
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # adds the type of the command and the length of the pin to the Pin.

        msg = command_type + str(len(verification_pin)) + verification_pin

        s.connect(self.__server_details)
        s.send(msg.encode())




class pin:
    @staticmethod
    # def __init__(self, defult_pin=0):
    #    self.__pin = defult_pin

    def create_pin():
        characters = string.ascii_letters + string.digits + string.punctuation
        verification_pin = str(''.join(random.choice(characters) for length in range(8)))
        return str(verification_pin)

我还使用 Json 文件来保存端口号和服务器 ip:

{ “负载”:{ “ip”:“10.100.102.94”,“端口”:12000 } }

暂无
暂无

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

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