socketserver TCPServer not working - python

According to the code on the book, I used TCPServer to create a TCP server and overrite the handle().
After build the connection, the server will print 'connected:' and client address.
but when I self.wfile.write() to send the data, either the server and client can't receive the data.
code of server:
from socketserver import (TCPServer as TCP, StreamRequestHandler as SRH)
HOST = ''
PORT = 1235
ADDR = (HOST, PORT)
class MyRequestHandler(SRH):
def handle(self):
print('connected:', self.client_address)
self.wfile.write('kkk'.encode('utf-8'))
tcpServ = TCP(ADDR, MyRequestHandler)
print('waiting for connection...')
tcpServ.serve_forever()
code of client:
from socket import *
HOST = 'localhost'
PORT = 1235
BUFSIZE = 1024
ADDR = (HOST, PORT)
while True:
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
data = input('>')
if not data:
break
tcpCliSock.send(data.encode("utf-8"))
data = tcpCliSock.recv(BUFSIZE).decode("utf-8")
if not data:
break
print(data)
tcpCliSock.close()

Related

How to manually shutdown a socket server?

I have a simple socket server, how do I shut it down when I enter "shutdown" in the terminal on the server side?
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
Close active connections and exit. It can be done with:
server.close()
exit(0)
To shutdown you socket server manually by calling server.close(), you whole code should be:
import socket
SERVER = "xxxx"
PORT = 1234
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_connection(conn, addr):
...
server.listen()
while True:
conn, addr = server.accept()
handle_connection(conn, addr)
# call server.close() to shut down your server.

How to protect data transmitted by socket?

This code is for sending and receiving between my PC and AWS Instance
I want to know whether the transmitted data is considered secure? or do I need something else to ensure the security of the transmitted data?
If the data is not encrypted, what is the addition to the code to make it secure?
code's client
import socket
HOST = "public ip of server"
PORT = 4444 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello, world")
data = s.recv(1024)
print(f"Received {data!r}")
server's code
server code
import socket
HOST = "0.0.0.0"
PORT = 4444 #open this in your router
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)

How do I connect to the internet through client's wifi? | Python

I've set up my server.py and client.py with the socket module, is there a way you can connect to the internet through the client? What i mean is, I want to have the server connect to the client through it's own internet, and then from there have the client use its internet to browse the web. But I have no idea how to do this.
So is there something I can leverage to achiece this?
Server:
import socket, threading
from time import sleep
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTIONS] {addr} connected')
while True:
conn.recv(6000)
conn.close()
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
thread = threading.Thread(target = handle_client, args = (conn,addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
print('[STARTNG] Server is starting')
start()
Client:
from time import sleep
import socket
PORT = 5430
SERVER = socket.gethostbyname(socket.gethostname())
FORMAT = 'utf-8'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
while True:
client.send('hi').encode(FORMAT)
conn.close()

Bad file descriptor when trying to send message from client to server

I need to be able to send a message as client to the server and get the message back from the server in my client's console.
However when I try to implement this I keep getting the error:
line 64, in <module>
s.send(message.encode('utf-8'))
OSError: [Errno 9] Bad file descriptor
My client:
import socket
HOST = 'localhost' # The server's hostname or IP address
PORT = 12000 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b'Hello, world')
data = s.recv(1024)
print('Received', repr(data))
while True:
message = input("write something:")
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print("Recieved from server: " + data)
My server:
import socket
HOST = 'localhost' # Standard loopback interface address (localhost)
PORT = 12000 # Port to listen on (non-privileged ports are > 1023)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)

Python socket exploiting client address and port for response

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

Categories

Resources