从本地主机上的简单套接字应用程序转到Web上

时间:2017-10-08 11:57:50

标签: python sockets p2p

我想学习如何编写p2p应用程序。我一直在玩套接字并拥有最基本的应用程序,如server.py

import socket
import sys

def main():
    host = "127.0.0.1"                   
    port = 5001
    mySocket = socket.socket()           
    mySocket.bind((host,port))
    mySocket.listen(1)                   
    print("Listening..")
    conn, addr = mySocket.accept()      
    print ("Connection from: " + str(addr))
    while True:
        data = conn.recv(1024).decode()
        if not data:                     
            break
        print ("From connected  user: " + str(addr))
        print ("Received from user: " + str(data))
        data = raw_input("Message: ")
        conn.send(data.encode())

if __name__ == '__main__':
    main()

client.py

import socket

def Main():
        host = '127.0.0.1'
        port = 5001
        mySocket = socket.socket()
        mySocket.connect((host,port))
        message = raw_input("Message: ")             # Need to send non unicode
        while message != 'q':                        # utf-8 binary code of unicode
                mySocket.send(message.encode())      # Encode utf-8 defualt
                data = mySocket.recv(1024).decode()  # Decode utf-8 default
                print ('Received from server: ' + data)
                message = raw_input("Message: ")
        mySocket.close()

if __name__ == '__main__':
    Main()

这在localhost上很有用。我的问题是我需要做什么才能在网上使用?例如。我给我的IP地址的人不在同一个网络上,他们可以连接。我希望能够在用户不必在其路由器设置中转发端口的情况下执行此操作。像bittorent和bitcoin这样的应用程序如何实现这一目标?

0 个答案:

没有答案