Python Messager局域网 [英] Python Messager LAN

查看:105
本文介绍了Python Messager局域网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试制作一个简单的python messager,得到相当多的连接无法到达的错误.我正在尝试使其成为peer2peer.有人还能建议如何做得更好吗,我在想添加某种循环来询问用户下一条消息,但是不确定如何去做.

Server.py

import socket

s = socket.socket()         
host = socket.gethostbyname(socket.gethostname())
port = 1337                
s.bind((host, port))        

s.listen(5)                 
while True:
   c, addr = s.accept()     
   print ("Got connection from", addr)
   c.send("Thank you for connecting to {0}".format(host).encode())
   msg1 = input("Enter Message: ")
   c.send(msg1.encode())
   msg2 = input("Enter Message: ")
   c.send(msg1.encode())
   msg3 = input("Enter Message: ")
   c.send(msg1.encode())
   msg4 = input("Enter Message: ")
   c.send(msg1.encode())

   c.close()                

Client.py

import socket               

s = socket.socket()         
host = "" 
port = 1337
s.bind((host, port))  

print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))

host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))

try:
      s.connect((host, port))
      s.listen(5)                 
      while True:
         c, addr = s.accept()     
         msg1 = input("Enter Message: ")
         c.send(msg1.encode())
         msg2 = input("Enter Message: ")
         c.send(msg1.encode())
         msg3 = input("Enter Message: ")
         c.send(msg1.encode())
         msg4 = input("Enter Message: ")
         c.send(msg1.encode())
except socket.error:
      print ("Host is unreachable")

input("Enter to lose")
s.close()               

谢谢.

解决方案

简单服务器(稍微修改了代码):

from threading import *
import socket

s = socket.socket()         
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)

def getMainThread():
    for thread in enumerate(): # Imported from threading
        if thread.name == 'MainThread':
            return thread
    return None

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.socket = socket
        self.address = address
        self.start() # Initated the thread, this calls run()

    def run(self):
        main = getMainThread()
        while main and main.isAlive():
            message = self.socket.recv(8192).decode('utf-8')
            self.socket.send(b"Got your message.. send another one!")
        self.socket.close()

while True:
   c, addr = s.accept()
   client(c, addr)

此服务器(无论是基本服务器)将处理多个客户端.

这是一个可行的客户端解决方案:

import socket               

print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))

host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))

sock = socket.socket()
try:
    sock.connect((host, 1337))
    while True:
        message = input("Enter Message: ")
        if message == 'quit':
            break
        sock.send(bytes(message, 'UTF-8'))
        recieved = sock.recv(8192).decode('utf-8')
        print('Server responded with:', recieved)
except socket.error:
     print ("Host is unreachable")

sock.close()

有关服务器的简短说明. 服务器的关键是要处理多个客户端,这要归功于一些基本线程. 每个连接的客户端都会被接受,然后抛出一个线程(当您调用client()时,它将初始化它自己的线程,而其余的应用程序将沿着该客户端线程的一侧继续进行.)

当主线程死掉时,所有客户端线程都应该死掉,例如,如果您抛出CTRL + C则应该中断,但在那里的错误处理需要更多的工作,并且您很可能最终会收到已在使用套接字"的信息. ",因为清理部门缺乏完善性. 但是您有了主意,就必须学会自己做一些工作:)

客户, 只要您不写退出",它就会首先以尽可能最干净的方式与服务器建立更多连接,并将永远向服务器发送和接收来自服务器的消息,直到(如上所述)您写出退出"为止.这样会断开连接并结束您的程序.

现在,所有这些操作就是向服务器发送一条消息,它会自动答复. 考虑创建以下内容:

clients = {}
...
clients[self.addr[0]] = self.socket

甚至

clients['Torxed'] = self.socket

允许您执行以下操作:

message = self.socket.recv(8192).decode('utf-8')
toWho = message.split(': ', 1)[0]
if toWho in clients:
    clients[toWho].send(bytes(message, 'UTF-8'))

这样,当客户写"Torxed:伴侣吗?"它将重定向到该客户端套接字.这只是一个非常简单明了的想法,向您展示您应该或至少可以做的事情.

可能令人困惑的事物

我注意到您写了很多s = ...c = ....
并且您在客户端发生了一些双重问题. 以事物的本质来称呼事物通常是个好习惯.例如, 在服务器中,您可以调用套接字server,但不能调用s. 或者,您只需保持它的简洁明了,并在两端将其称为socket,除了在某些网格区域中,无论出于何种原因您都可以创建多个服务器实例套接字(桥接服务器或其他).

请记住,解决方案越简单又简短..越有可能您会记住为什么以及如何解决它.不要过于关注解决方案.

例如,您的服务器具有与我的解决方案相同的代码行数(我知道这不是完美的),但是我设法挤入线程,并且如果我/您也拥有朋友列表". . 充分利用循环,函数和其他东西.它们将挽救您的生命:)

也请注意

如果您打算使用socket作为客户端,则不需要要做s.bind(())s.listen(5),这是服务器端属性.

Trying to make a simple python messager, getting quite aconnection unreachable error. I am trying to make it peer2peer. Could anyone also suggest how to make it better, I was thinking of adding a loop of some sort to ask the user for the next message, not sure how to go about doing this however.

Server.py

import socket

s = socket.socket()         
host = socket.gethostbyname(socket.gethostname())
port = 1337                
s.bind((host, port))        

s.listen(5)                 
while True:
   c, addr = s.accept()     
   print ("Got connection from", addr)
   c.send("Thank you for connecting to {0}".format(host).encode())
   msg1 = input("Enter Message: ")
   c.send(msg1.encode())
   msg2 = input("Enter Message: ")
   c.send(msg1.encode())
   msg3 = input("Enter Message: ")
   c.send(msg1.encode())
   msg4 = input("Enter Message: ")
   c.send(msg1.encode())

   c.close()                

Client.py

import socket               

s = socket.socket()         
host = "" 
port = 1337
s.bind((host, port))  

print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))

host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))

try:
      s.connect((host, port))
      s.listen(5)                 
      while True:
         c, addr = s.accept()     
         msg1 = input("Enter Message: ")
         c.send(msg1.encode())
         msg2 = input("Enter Message: ")
         c.send(msg1.encode())
         msg3 = input("Enter Message: ")
         c.send(msg1.encode())
         msg4 = input("Enter Message: ")
         c.send(msg1.encode())
except socket.error:
      print ("Host is unreachable")

input("Enter to lose")
s.close()               

Thanks.

解决方案

Simple server (reworked your code a bit):

from threading import *
import socket

s = socket.socket()         
host = socket.gethostbyname(socket.gethostname())
port = 1337
s.bind((host, port))
s.listen(5)

def getMainThread():
    for thread in enumerate(): # Imported from threading
        if thread.name == 'MainThread':
            return thread
    return None

class client(Thread):
    def __init__(self, socket, address):
        Thread.__init__(self)
        self.socket = socket
        self.address = address
        self.start() # Initated the thread, this calls run()

    def run(self):
        main = getMainThread()
        while main and main.isAlive():
            message = self.socket.recv(8192).decode('utf-8')
            self.socket.send(b"Got your message.. send another one!")
        self.socket.close()

while True:
   c, addr = s.accept()
   client(c, addr)

This server (altho yet basic) will handle multiple clients.

And here's a working client solution:

import socket               

print("""
================================================================================
Welcome to Coder77's local internet message for avoiding surveillance by the NSA
================================================================================
The current soon to be encrypted server is {0}
""".format(host))

host = input("Please select the IP you would like to communicate to: ")
print("Now connecting to {0}....".format(host))

sock = socket.socket()
try:
    sock.connect((host, 1337))
    while True:
        message = input("Enter Message: ")
        if message == 'quit':
            break
        sock.send(bytes(message, 'UTF-8'))
        recieved = sock.recv(8192).decode('utf-8')
        print('Server responded with:', recieved)
except socket.error:
     print ("Host is unreachable")

sock.close()

Short about the server. The point of a server is to handle multiple clients, this one will thanks to some basic threads. Each client that connects, gets accepted and then thrown into a thread (when you call client() it will initate it's own thread and the rest of the application will continue along side of that clients thread).

All client threads should die when the main thread dies, for instance if you throw a CTRL+C it shouold break but the error handling there needs more work, and you'll most likely end up with a "Socket already in use" because of lack of perfection in the cleanup department. But you get the idea and you'll have to learn to do some work yourself :)

The client, as long as you don't write "quit" it will first and for more connect to a server in the cleanest way possible, and will forever SEND+Recieve messages to and from the server, until (as mentioned) you write "quit". That will disconnect and end your program.

Now, All this does, is send a message to the server and it auto-replies. Consider creating something such as:

clients = {}
...
clients[self.addr[0]] = self.socket

or even

clients['Torxed'] = self.socket

Enabling yo to do stuff like:

message = self.socket.recv(8192).decode('utf-8')
toWho = message.split(': ', 1)[0]
if toWho in clients:
    clients[toWho].send(bytes(message, 'UTF-8'))

So that when a client writes 'Torxed: Hey whats up mate?' it will get redirected to that client socket. That's just a completely simple and plain idea to show you what you should or at least could do.

Things that might be confusing

I noticed you wrote s = ... and c = ... quite a lot.
And you had some double-socket thing going on in the client..? Calling things for what they are is usually good practice.. for instance, In the server you could call the socket server but never s. Or you just keep it clean and simple and call it socket in both ends except in some rair occations where you might create multiple server-instance sockets for whatever reason (bridging servers and what not).

And remember, the easier and short the solution is.. The more probable it is that you'll remember why and how you solved it. Don't go overboard on solutions.

Your server for instance, had about the same number of lines of code as my solution had (mine is not perfect i know), but i managed to squeeze in threading and if i/you wnated to also a "friendslist".. Take good use of loops, functions and stuff.. They'll save your life :)

Also note

That if you intend to use the socket as a client, you don't need to do s.bind(()) or s.listen(5), that's server-side properties.

这篇关于Python Messager局域网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆