i Try to create udp port listener using OOP but i try to start server it not start. In python console it only show
=============RESTART: D:\server.py==================
>>>
this is my code
import threading
import time
import socket
class udpreceive:
def __init__(self,port,ip):
self.port = port
self.ip = ip
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind((self.ip, self.port))
def startserver(self):
while True:
time.sleep(1)
data, addr = self.sock.recvfrom(1024)
print (data)
server1 = udpreceive(514,"192.168.1.5")
t1 = threading.Thread(target=server1.startserver)
what is the error? I'm new to OOP and socket programming Thanks
Related
I'm creating a program that uses threads to handle sockets and input at the same time. I've narrowed down the errors I'm getting to be replicable in these couple dozen lines of code. What happens to anyone else who runs the code below? I encounter a hang-up in waiting for the recv in the client. If I further try to send() more data in the server, I get a Broken Pipe error. And, even more weirdly, if I comment out the line that calls input(), the sockets work just fine.
What kind of weird interaction is going on between input(), sockets, and threading? And does anyone have a solution to this? Here's some code that generates the error.
Server:
import socket
import threading
def handle_connection(conn, addr):
data = conn.recv(1024)
message = data.decode('ascii').split()
s = "TEST"
conn.send(bytes(s, 'ascii')) #
conn.close()
def handle_input():
while True:
s = input()
print(s)
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 2000 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT)); #Empty first string = INADDR_ANY
s.listen();
w = threading.Thread(target=handle_input)
w.start()
while True:
conn, addr = s.accept()
x = threading.Thread(target=handle_connection, args=(conn, addr))
x.start()
s.close()
Client:
import socket
HOST = "127.0.0.1" # The server's hostname or IP address
PORT = 2000 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
message = "find_successor a"
s.connect((HOST, PORT))
s.sendall(bytes(message, 'ascii'))
data = s.recv(1024)
print(f"Received {data!r}")
I appreciate any help or insight!
(I have the following code in which I would like to implement a server-side application and to send clients a response:
class client(Thread):
def __init__(self, socket, address):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.start()
def run(self):
request = ''
while 1:
data = self.sock.recv(1024).decode() # The program hangs here with large message
if not data:
break
request += data
print(request, self.addr[1], self.addr[0]))
message = "test"
self.sock.send(message.encode())
def init_server():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((host, int(port)))
serversocket.listen(5)
while 1:
clients, address = serversocket.accept()
client(clients, address)
return
Now I write a simple client:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 8000))
client_socket.send(message)
request = ''
while 1:
data = client_socket.recv(2048).decode()
if not data:
break
request += data
print(request)
client_socket.close()
The problem now is that the server hangs in recv with a large message. How can I solve it?
Your client socket and server socket are different sockets.
You can get server info using the serversocket object the same way you try self.sock.
I would recommend parsing serversocket as a third argument into your client class, and then using it within the class like so:
class client(Thread):
def __init__(self, socket, address, server):
Thread.__init__(self)
self.sock = socket
self.addr = address
self.server = server
self.start()
def run(self):
request=''
while 1:
data=self.sock.recv(1024).decode()
if not data:
break
request+=data
print(request, self.server.getsockname()[1], self.server.getsockname()[0]))
def init_server():
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((host, int(port)))
serversocket.listen(5)
while 1:
clients, address = serversocket.accept()
client(clients, address, serversocket)
return
That should output the server information.
If you wanted the client information, it's parsed in the 'address' as a tuple, you can see the remote IP address and the socket port used to communicate on (not the open port).
Most of all, my question is pretty similar to the following : Cannot access Python server running as Windows service. I tried the solution but it doesn't solve my problem.
I was able to connect a client and a server by using the Python Socket Tutorial :
# Echo server program
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
# Echo client program
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
and It worked like a charm, then I coded the following Windows Service :
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import logging
import sys
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "PySvc"
_svc_display_name_ = "PySvc"
_svc_description_ = "PySvc"
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
logging.basicConfig(filename='C:/test.log',
level =logging.DEBUG,
format ='%(asctime)s %(message)s',
filemode='w')
rc = None
self.HOST = '' # Symbolic name meaning the local host
self.PORT = 50007 # Arbitrary non-privileged port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.bind((self.HOST, self.PORT))
logging.debug("BIND")
self.s.listen(1)
logging.debug("LISTENED")
self.conn, self.addr = self.s.accept()
logging.debug("ACCEPT")
logging.debug("connected to " + str(self.addr))
self.s.setblocking(1)
logging.debug("set blocking")
# if the stop event hasn't been fired keep looping
while rc != win32event.WAIT_OBJECT_0:
# block for 5 seconds and listen for a stop event
rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)
self.main()
def main(self):
pass
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
But the connexion is never accepted by the service. the log contains :
2018-03-19 16:37:48,967 BIND
2018-03-19 16:37:48,967 LISTENED
If I do a netstat :
NETSTAT -an | find /i "listening"
I find the following line, which show that the server is listening :
TCP 0.0.0.0:50007 0.0.0.0:0 LISTENING
Can someone explain me why it doesn't work ?
I made this basic Python 3 socket server in an attempt to learn socket programming. I can connect to it using 'telnet 192.168.x.x 9001' on the same computer, running Ubuntu 16.04, but when I try using my other computer on a different network, Windows 10, on a different network it wont let me connect (when using the computer running Windows 10, I run the serve on Ubuntu).
This is the code I have written.
import socket
from _thread import start_new_thread
host = ""
port = 9001
class Server:
def __init__(self, host, port):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
self.server.bind((host, port))
except socket.error as e:
print(str(e))
self.server.listen(10)
def main(self, conn):
while True:
conn.send(str.encode("Enter some text to make uppercase: "))
message = conn.recv(4096)
message = str(message,'utf-8')
conn.send(str.encode(message.upper()))
def run(self):
while True:
conn, addr = self.server.accept()
print("Connection from {}:{:d}".format(addr[0], addr[1]))
start_new_thread(self.main, (conn, ))
my_server = Server(host, port)
my_server.run()
I am trying to create a socket IN A THREAD, but i am unable to do so.
My code is
#!/usr/bin/env python
import threading
import socket
class test1():
def serve(self):
host = ''
port = 9999
th_obj = threading.Thread(target = self.thread_method, args = (host,port))
th_obj.daemon = True
th_obj.start()
def thread_method(self,host,port):
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
sock.bind(('',9999))
sock.listen(5)
while True:
connection, addr = sock.accept()
connection.settimeout(60)
while True:
data = connection.recv(2048)
t = open('file.txt', 'a')
t.write(data)
test1().serve()
The problem is the script won't when I set daemon = True while it is working perfectly without it.
How can i solve this problem. It is essential to me to demonize it.