Cannot run multiple files when connected to Server in VSCode Python - python

I am trying to test connections to a server from a network. I have 2 seperate files; server.py and network.py.
My server.py works as it says "Server Started" but when I try to run network.py to connect to the server, it does not let me run it. I am doing this in VSCode so I don't know if its a software bug.
I have provided the server.py code and network.py code (They are in the same workspace and directory) and for privacy I have hidden my IP address
Server.py:
import socket
from _thread import *
import sys
server = "XXXXXX" # server address on LAN
port = 5555 # 5555 is an open safe port for use
socket_x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# .AF_INET allows sokcet to communicate with addresses
# SOCK_STREAM IS USED BY TCP SERVER WHICH ALLOWS DEVICES TO TRANSMIT DATA TO ONE ANOTHER
try: # check for socket errors
socket_x.bind((server, port)) # creating server
except socket.error as e:
str(e)
socket_x.listen(2) # allows for connections (2 people can connect)
print("Waiting for Connection, Test Server Started")
def threaded_client(conn):
conn.send(str.encode("Connected"))
reply = ""
while True:
try:
data = conn.recv(2048)
reply = data.decode("utf-8")
if not data:
print("Disconnected")
break
else: # if there is data
print("Recieved: ", reply)
print("Sending: ", reply)
conn.sendall(str.encode(reply))
except:
break
print("Lost connection")
conn.close()
while True: # continuosly looking for connections
conn, address = socket_x.accept() # accept any incoming connections and store into variables
print("Connected to:", address)
# start_new_thread(threaded_client, (conn, ))
start_new_thread(threaded_client, (conn, ))
Network.py:
import socket
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "XXXXXX" # will always be the same
self.port = 5555
self.address = (self.server, self.port)
self.id = self.connect()
print(self.id)
def connect(self):
try: # trying to connect
self.client.connect(self.address)
return self.client.recv(2048).decode()
except:
pass
n = Network()
Thank you for the help

Related

Having trouble connecting to a local server in Python

I'm currently following this tutorial on how to make a multiplayer game using python: https://www.youtube.com/watch?v=McoDjOCb2Zo
I'm currently trying to connect to a server file with a network file. Running the server file prints out the correct piece of information but once I try connecting to it with the network file nothing happens.
Here is my server code. When it runs it prints out "Waiting for a connection, Server started
(I have removed my IP address, but I know that I have the right one in for when I run my code)
import socket
from _thread import *
server = "***.***.*.**"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waitng for a connection, Server Started")
def threaded_client(conn):
conn.send(str.encode("Connected"))
reply = ""
while True:
try:
data = conn.recieve(2048)
reply = data.decode("utf-8")
if not data:
print("Disconnected")
break
else:
print("Received", reply)
print("Sending: ", reply)
conn.sendall(str.encode(reply))
except:
break
print("Lost Connection")
conn.close()
while True:
conn, addr = s.accept()
print("Conneced to: ", addr)
start_new_thread(threaded_client, (conn,))
And here is the code for my network
import socket
class Network:
def __init__(self):
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server = "***.***.*.**"
self.port = 5555
self.addr = (self.server, self.port)
self.id = self.connect()
print(self.id)
def connect(self):
try:
self.client.connect(self.addr)
return self.client.recv(2048).decode()
except:
pass
n = Network()
When I run this code after initializing the server, it is supposed to print out "Connected"

Python sockets and commands

I'm trying to send console commands from one machine to another using Python sockets. I want the server to send back the results of the command to the client. If the client types "ls" I want the server to send back the results of running that command. Instead of the expected result, the server just says "action completed: ls". How can I fix this so the server will run the expect commands and return the result?
Server:
import socket
from subprocess import call
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print('Connection established: ' + str(addr))
while True:
try:
data = c.recv(1024).decode('utf-8')
print('sending data: ' + data)
c.send(data.encode('utf-8'))
if data == 'q':
break
except NameError:
error = 'Command does not exist'
c.send(error.encode('utf-8'))
continue
except SyntaxError:
error = 'Command does not exist'
c.send(error.encode('utf-8'))
continue
c.close()
Client:
import socket
from subprocess import call
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
message = str(input('> '))
while message != 'q':
try:
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print('Action completed: %s' % data)
message = str(input('> '))
except NameError:
print("Command not recognized.")
continue
except SyntaxError:
print("Command not recognized")
continue
I recently built a socket connection in order to communicate with an android device.
I decided to use UDP instead of TCP (which is what you did). For UDP as well as TCP you need a sender and a receiver on both sides of the communication.
The port number that is received in the "addr" variable changes with every connection, so you cannot use it.
What I did, I assigned two different ports one for sending from A to B and the other port to send from B to A.
Here is my server code:
import socket # socket connection
import threading # Multithreading
import time # Timeing
# ----------------------------------------------
# Variables
# ----------------------------------------------
UDPListen2Port = 12345
UDPSend2Port = 123456
Listen2IP = '' # input your local IP here
# ----------------------------------------------
# Threading class
# ----------------------------------------------
class signalProcessingThread(threading.Thread):
def __init__(self, iP, cmdIn):
threading.Thread.__init__(self)
self.iP = iP
self.cmdIn = cmdIn
def run(self):
print("Recv--", self.iP ,"--", self.cmdIn) # Display Thread Info
cmdOut = self.EvalMessage() # Actual signal processing
byteOut = bytes(cmdOut.encode("utf-8")) # Convert Server reply to bytes
sock.sendto(byteOut,(self.iP,UDPSend2Port)) # Send Server Reply to Socket
# ----------------------------------------------
# Initialize Socket
# ----------------------------------------------
sock = socket(AF_INET, SOCK_DGRAM) # -- UDP -- connection
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) # in case the port was not properly closed before
sock.bind((Listen2IP,UDPListen2Port)) # bind to the port
# ----------------------------------------------
# Listen to Socket
# ----------------------------------------------
while True:
try: # wait for a connection
data,addr = sock.recvfrom(66507) # number of bytes in the message
msg = data.decode('utf-8')
newThread = signalProcessingThread(addr[0],msg)
newThread.start()
except KeyboardInterrupt:
print('Connection failed')
sock.close()
sock.close()
The client code is quite similar, with the difference that it doesn't necessarily need to run in a thread. Hope I could help.

Error: Transport endpoint is not connected (Python Sockets)

I'm trying to create a simple chat application using sockets in Python (with threads). Application is simple client has to threads one to send data and another to receive. Server has to two threads one to accept client connection and another to broadcast the message. But on running the below code, I'm getting error message
Transport endpoint is not connected
Can anybody tell me why I'm getting this error
Client
import socket, threading
def send():
msg = raw_input('Me > ')
cli_sock.send(msg)
def receive():
data = cli_sock.recv(4096)
print('> '+ str(data))
if __name__ == "__main__":
# socket
cli_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connect
HOST = 'localhost'
PORT = 5028
cli_sock.connect((HOST, PORT))
print('Connected to remote host...')
thread_send = threading.Thread(target = send)
thread_send.start()
thread_receive = threading.Thread(target = receive)
thread_receive.start()
Server
import socket, threading
def accept_client():
while True:
#accept
cli_sock, cli_add = ser_sock.accept()
CONNECTION_LIST.append(cli_sock)
print('Client (%s, %s) connected' % cli_add)
def broadcast_data():
while True:
data = ser_sock.recv(4096)
for csock in CONNECTION_LIST:
try:
csock.send(data)
except Exception as x:
print(x.message)
cli_sock.close()
CONNECTION_LIST.remove(cli_sock)
if __name__ == "__main__":
CONNECTION_LIST = []
# socket
ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind
HOST = 'localhost'
PORT = 5028
ser_sock.bind((HOST, PORT))
# listen
ser_sock.listen(1)
print('Chat server started on port : ' + str(PORT))
thread_ac = threading.Thread(target = accept_client)
thread_ac.start()
thread_bd = threading.Thread(target = broadcast_data)
thread_bd.start()
You're using server sockets incorrectly. You cannot recv on server sockets, instead you accept connections on them; accept returns the actual connection socket:
ser_sock.listen(1)
sock, addr = ser_sock.accept()
print('Got connection from {}'.format(addr))
# only this *connection* socket can receive!
data = sock.recv(4096)

Socket based chat program doesn't work correctly

I'm trying to create a chatroom based on sockets which works on windows.
I have a server script:
# chat_server.py
import sys
import socket
import select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 9009
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(10)
threads = []
#add server socket object to the list of readable connections
SOCKET_LIST.append(server_socket)
print("Chat server started on port " + str(PORT))
while 1:
# get the list sockets wich are ready to be read through select
# 4th arg, tiome_out = 0 : poll and never block
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
for sock in ready_to_read:
# a new connection request recieved
if sock == server_socket:
sockfd, addr = server_socket.accept()
SOCKET_LIST.append(sockfd)
print("Cient (%s, %s) connected" % addr)
broadcast(server_socket, sockfd, "[%s:%s] entered our chatting room\n" % addr)
# a message from a client, not a new connection
else:
# process data recieved from client,
try:
#receiving data from the socket.
data, addr = sock.recvfrom(RECV_BUFFER)
if data:
# there is something in the socket
broadcast(server_socket, sock, "\r" + '[' + str(sock.getpeername()) + ']' + data)
else:
# remove the socket that's broken
if sock in SOCKET_LIST:
SOCKET_LIST.remove(sock)
# at this stage, no data means probably the connection has been broken
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
# exception
except:
broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
continue
server_socket.close()
# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
for socket in SOCKET_LIST:
# send the message only to peer
if socket != server_socket and socket != sock :
try :
socket.send(message)
except :
# broken socket connection
socket.close()
# broken socket, remove it
if socket in SOCKET_LIST:
SOCKET_LIST.remove(socket)
if __name__ == "___main__":
sys.exit(chat_server())
chat_server()
And a client script:
# chat_client.py
import sys
import socket
import select
from threading import Thread
def chat_client():
if(len(sys.argv) < 3):
print('Usage: python chat_client.py hostname port')
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
#connect to remote host
try:
s.connect((host,port))
except:
print('Unable to connect')
sys.exit()
print('Connected to remote host. You can start sending messages')
sys.stdout.write('[Me] '); sys.stdout.flush()
sock_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock_send.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock_send.bind((host, port))
def send_msg(sock):
while True:
# user entered a message
s.send(sys.stdin.buffer.readline())
sys.stdout.write('[Me] '); sys.stdout.flush()
def recv_msg(sock):
while True:
# incoming message from remote server, s
data, addr = sock.recvfrom(1024)
if not data :
print('\nDisconnected from chat server')
sys.exit()
else:
#print data
sys.stdout.write(data)
sys.stdout.write('[Me] '); sys.stdout.flush()
Thread(target=send_msg, args=(sock_send,)).start()
Thread(target=recv_msg, args=(sock_send,)).start()
if __name__ == "__main__":
sys.exit(chat_client())
The program is executed with:
$ python chat_server.py
$ python chat_client.py localhost 9009
If I run the code I won't get any Error. When I run several clients at the same time they all connect to the server correctly, but one client doesn't get the text another client has written.
I think something is wrong with the server's broadcast function, but I'm not sure what it is.
I already searched for similar questions, but I didn't find anything useful for fixing this problem. Please Help!

How to make a simple multithreaded socket server in Python that remembers clients

How do I make a simple Python echo server that remembers clients and doesn't create a new socket for each request? Must be able to support concurrent access. I want to be able to connect once and continually send and receive data using this client or similar:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = raw_input("Server hostname or ip? ")
port = input("Server port? ")
sock.connect((host,port))
while True:
data = raw_input("message: ")
sock.send(data)
print "response: ", sock.recv(1024)
I.e. with the server running on port 50000, using the above client I want to be able to do this:
me#mine:~$ client.py
Server hostname or ip? localhost
Server Port? 50000
message: testa
response: testa
message: testb
response: testb
message: testc
response: testc
You can use a thread per client to avoid the blocking client.recv() then use the main thread just for listening for new clients. When one connects, the main thread creates a new thread that just listens to the new client and ends when it doesn't talk for 60 seconds.
import socket
import threading
class ThreadedServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
def listen(self):
self.sock.listen(5)
while True:
client, address = self.sock.accept()
client.settimeout(60)
threading.Thread(target = self.listenToClient,args = (client,address)).start()
def listenToClient(self, client, address):
size = 1024
while True:
try:
data = client.recv(size)
if data:
# Set the response to echo back the recieved data
response = data
client.send(response)
else:
raise error('Client disconnected')
except:
client.close()
return False
if __name__ == "__main__":
while True:
port_num = input("Port? ")
try:
port_num = int(port_num)
break
except ValueError:
pass
ThreadedServer('',port_num).listen()
Clients timeout after 60 seconds of inactivity and must reconnect. See the line client.settimeout(60) in the function ThreadedServer.listen()

Categories