python socket server is hanging after sending data - python

I made a python socket server recently that listens on port 9777 the server is suppose to accept connections and once it does will allow you to send information to the client. The client will then print out whatever it received. However, I found that after I sent some data the server would hang until i reinitialized a new connection. Is there a reason for this and if so how can I prevent it from happening
The code of the server is :
import socket
import sys
host='0.0.0.0'
port=9777
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(10)
c,a=s.accept()
while True:
command=raw_input('[input>] ')
if 'data' in command:
c.send('continue')
data=c.recv(1024)
print data
else:
continue
the code will only send data if the word data is in the string. Here is the code for the client:
import socket
import sys
host='192.168.0.13'
port=9777
while True:
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
except:
continue
while True:
d=s.recv(9999)
print d
s.send('received')
My goal is to setup a connection between server and client. I want the server to be able to accept input from a user in a while loop and send the input to the client. The client needs to be able to receive information and when it does it will send a response to the server. Then the user can continue sending data to the server until they decide to terminate the program. However the server keeps hanging after sending data once to the client. Can anyone tell me how I can prevent that?

I try this code in my computer it's work fine , maybe you need to change host='192.168.0.13' to host='localhost'
and host='0.0.0.0' to host='localhost'
look at this picture
and if this problem stay maybe your ip address is the same of other device in the network for that try to run this command ipconfig /renew

Related

Simple TELNET in Python - loop paused if no data coming

I'm trying to build a very simple TELNET client in Python and I'm getting problem on the last part: sending/receiving data to/from the server.
With the code I have, if no data arrives at the very beginnig, the loop get paused and I can't even send commands.
Here the interested part of the code:
# Infinite cycle that allows user to get and send data from/to the host
while True:
incoming_data = my_socket.recv(4096)
if not incoming_data:
print('Problem occurred - Connection closed')
my_socket.close()
sys.exit()
else:
# display data sent from the host trough the stdout
sys.stdout.write(incoming_data)
# Commands sent to the host
command = sys.stdin.readline()
my_socket.send(command)
(I think the program kinda of works if I try to connect to some hosts that send data at the beginning.)
The idea would be have two loops, running at the same time, getting data or sending data, but I can't get it to work.
I can't use the telnet library and I don't want to use the select library (only sys and socket).
You want to use the threading library.
The following program runs the receiving in one thread and the sending in another:
import socket
from threading import Thread
def listen(conn):
while True:
received = conn.recv(1024).decode()
print("Message received: " + received)
def send(conn):
while True:
to_send = input("Input message to send: ").encode()
conn.sendall(to_send)
host = "127.0.0.1"
port = 12345
sock = socket.socket()
sock.connect((host, port))
Thread(target=listen, args=[sock]).start()
Thread(target=send, args=[sock]).start()
This program is for Python 3. Python 2 is very similar, except print() works differently, and you don't need to encode() and decode() everything being sent through a socket.
The listen and send functions are run in parallel, so that as soon as data arrives, it is printed, but you can also send data at any time. Practically, you would probably want to make some changes so that the data isn't just printed over the input prompt. However, this would be hard just in a command line application.
Research queues for control over data passing between threads.
Let me know if you have any more questions.

How to interact with Remote Server using Python Sockets

I am trying to connect to a server using python sockets. I am able to make a connection and fetch the response data. However, I want the socket communication to be interactive from the client side.
For instance, if I use netcat to connect to the server, the communication is interactive:
nc aa.bb.cc.dd 1234
Server greets you
I can enter the input here
Server responds to my input
However, when I make the connection using python sockets, all I receive is the greeting from the Server and program completes execution.
Here is the python code I am using:
#! /usr/bin/python
import os
import sys
import socket
host = "aa.bb.cc.dd"
port = 1234
remote_ip = socket.gethostbyname(host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_ip, port))
print s.recv(1024)
I want to modify the above python program so that I can send inputs to the Server as well.
Thanks.
Usually you do
input_data = input("Enter something: ")
s.send(bytes(input_data,'utf-8'))
You could use a while loop to get user input, send to server, and get a response continuously.
while True:
print(str(s.receive(1024)))
toSend = input()
s.send(bytes(toSend, "utf-8"))

Socket programming stuck waiting for a response from the server

For a class assignment I need to use the socket API to build a file transfer application. For this project there two connections with the client and server, one is called the control and is used to send error messages and the other is used to send data. My question is, on the client side how can I keep the control socket open and waiting for any possible error messages to be received from the server while not blocking the rest of the program from running?
Example code (removed some elements)
#Create the socket to bind to the server
clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((serverName,portNum))
clientSocket.send(sendCommand) # Send to the server in the control connection contains either the list or get command
(If command is valid server makes a data connection and waits for client to connect)
clientData = socket(AF_INET,SOCK_STREAM)
clientData.connect((serverName,dataport)) #Client connects
recCommand = clientData.recv(2000) #Receive the data from server if command is successful
badCommand = clientSocket.recv(2000) #But if there is an error then I need to skip the clientData.recv and catch the error message in bad Command
when there is an error, the data-socket should be closed by the server, so recv ends automatically.

Receiving files python socket server

I was trying to create a python socket server that could send and receive data, so I created a socket on the server using the code here:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 1208))
serversocket.listen(5)
(client,(ip,port)) = serversocket.accept()
Then I tried to create a sample connection from my machine by going to command prompt and typing
telnet www.filesendr.com 1208
However, the console simply replies with "Could not open connection to the host, on port 1208...Connection failed." I went back over my code but couldn't identify the problem. Any help would be greatly appreciated.
I think part of the problem is that after you accept the connection you don't do anything else. Once the accept happens, you get to the end of the script, python exits and closes all open file handles (including the socket you just opened). If you want to be able to talk to yourself through telnet, try something like this:
import socket
import select
import sys
port = 1208
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind(('',port))
listener.listen(128)
newSock, addr = listener.accept()
while True:
r,w,e = select.select([newSock,sys.stdin],[],[])
if newSock in r:
data = newSock.recv(4096)
sys.stdout.write(data)
if sys.stdin in r:
newSock.send(sys.stdin.readline())

socket in python

i tried to do client and server and look what i do
#Server
import socket
Host=''
Port=305
OK=socket.socket()
OK.bind((Host,Port))
OK.listn(1)
OK.accept()
and another one for client
#Client
impot socket
Host='192.168.1.4'
Port=305
OK=socket.socket()
OK.connect((Host,Port))
First thing : for now every thing is ok but i want when client connect to server :
server print "Hello Admin" in client screen
second thing : i want make like input command ! like
COM=raw_input('enter you command system:')
then client enter dir for example then server print the result in client screen
Look here, this is a simple echo server written in Python.
http://ilab.cs.byu.edu/python/socket/echoserver.html
When you create a connection, the story isn't over. Now it's time to send data over the connection. Create a simple "protocol" (*) and use it to transfer data from client to server and/or back. One simple example is a textual protocol of commands separated by newlines - this is similar to what HTTP does.
(*) Protocol: an agreement between two parties on the format of their communication.
I think you might want to do something like this:
client, addr = OK.accept()
client.send("Hello Admin")
And then use
data = client.recv(1024)
to get data from the client.
If you want to get command input from the client, you just need to execute the commands the client sends and send the output back back to the client.
from commands import getoutput
client.send(getoutput(client.recv(1024)))
Thats about the easiest solution possible.
For Client:
import os
import sys
impot socket
Host=raw_input ("Please enter ip : ")
Port=raw_input ("please Enter port :")
OK=socket.socket()
OK.connect((Host,Port))
print " Enter Command")
cmd = raw_input()
os.system(cmd)
I think that your codes has an issue:
you seem to have OK = socket.socket(), but I think it should be:
OK = socket.socket(socket.AF_INET, socket.STREAM), which would help if your making a connection. And your server has a problem: OK.listn(1) should be OK.listen(1). And, don't forget about send() and recv().
#Client
import socket
Host='192.168.1.4'
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.connect((Host,Port))
while True:
com = raw_input("Enter your command: ")
OK.send(com)
data = OK.recv(5000) #Change the buffer if you need to, I have it setup to run 5000
print "Received:\n" + data
which should work for the client
#Server
import socket
import os
Host=''
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.bind((Host,Port))
OK.listen(1)
conn, addr = OK.accept()
while True:
data = conn.recv(2048) #Change the buffer if needed
if data == "":
break
r = os.system(data)
conn.send(str(r)) #Note this will send 0 or 1, 0 = ran, 1 = error
Note: These fixes would work for Windows, I don't know about Unix systems.*

Categories

Resources