Python. Socket closes after one input - python

I am doing an simple Python socket server and client that need to be able to receive few inputs and not losing connection. I can input one command but after receiving the reply the connection is lost. How can i keep it alive?
Client code
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except sockets.error , msg:
print 'Failed to create socket, Error code:' + str(msg[0]) + ' , Error message :' + msg[1]
sys.exit()
print 'Socket Created'
host = '127.0.0.1'
port = 8888
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
except socket.error:
print 'Send failed'
sys.exit()
print 'Message send successfully'
reply = s.recv(4096)
print reply
s.close()
Server code
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
from thread import *
import glob
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
def clientthread(conn):
while True:
data = conn.recv(1024)
if data == "show dir":
reply = glob.glob('*.*')
else:
reply ="Þessi skipun hefur ekki verið forrituð"
if not data:
break
conn.send(str(reply))
while 1:
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()

Your server code looks okay. But your client is only sending one message and then exiting. Which closes the connection.
Try something like this in your client code:
while True:
message = raw_input('Sladu inn skipun :')
try :
s.sendall(message)
print s.recv(1024)
except socket.error:
print 'Send failed'
sys.exit()

Related

How to have two TCP servers in one python code

I am new to socket programming and I am trying to write a python program for a client which also acts as a server. I need 2 listening TCP servers in 1 code.
The client part is looped 5 times to create 5 client instances.
The Server part is supposed to listen to 50 clients at the same time.
While I am able to make client and 1 server in the same code, the 2nd server wont connect.
I will be very grateful if someone could help me.
I am attaching the code below.
import socket
count = 1
port1 = 12345
x=range(5)
for n in x:
ClientSocket = socket.socket()
host = '127.0.0.1'
port = 1233
print('Waiting for connection here')
try:
ClientSocket.bind(('',port1))
ClientSocket.connect((host, port))
except socket.error as e:
print(str(e))
Response = ClientSocket.recv(1024)
Input = 'ServerMini'+str(count)
ClientSocket.send(str.encode(Input))
Response1 = ClientSocket.recv(1024)
print(Response.decode('utf-8'))
print(Response1.decode('utf-8'))
ClientSocket.close()
port1 = port1+1
count = count+1
ClientSocket.close()
import os
from _thread import *
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 12345
porta = 12346
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection):
connection.send(str.encode('Welcome to the Servern'))
# while True:
data = connection.recv(2048)
print (data)
print (port)
reply = 'Server1 Says: ' + data.decode('utf-8') + 'connected' + '12345'
# if not data:
# break
connection.sendall(str.encode(reply))
connection.close()
x=range(50)
for n in x:
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()
# import os
# from _thread import *
# ServerSocket = socket.socket()
# host = '127.0.0.1'
# port = 12346
# ThreadCount = 0
try:
ServerSocket.bind((host, porta))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection):
connection.send(str.encode('Welcome to the Servern'))
# while True:
data = connection.recv(2048)
print (data)
print (port)
reply = 'Server2 Says: ' + data.decode('utf-8') + 'connected' + '12345'
# if not data:
# break
connection.sendall(str.encode(reply))
connection.close()
x=range(50)
for n in x:
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSocket.close()

Python socket server not printing the received data?

I am sending a string from a python client to a python socket server
here is the server side code where i am printing the received value :
def threaded_client(connection):
while True:
data = connection.recv(2048)
print(data)
datatemp = data.decode('utf-8')
print(datatemp)
message = datatemp.split('_')
print(message[0])
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ServerSocket.close()
and on the server side i am printing print(data) , print(datatemp) and lit('_') but non of these print statements is printing anything
What am i doing wrong ?
UPDATE 1:
I am using these Imports:
import socket
import os
from _thread import *
Here is the full server code :
import socket
import os
from _thread import *
ServerSocket = socket.socket()
host = '127.0.0.1'
port = 34534
ThreadCount = 0
try:
ServerSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Waitiing for a Connection..')
ServerSocket.listen(5)
def threaded_client(connection):
while True:
data = connection.recv(2048)
print(data)
datatemp = data.decode('utf-8')
print(datatemp)
message = datatemp.split('_')
print(message[0])
while True:
Client, address = ServerSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ServerSocket.close()

Python: Close socket after specific time whether the client connected to it or not

First off, Im a python beginner, so I'm not really experienced.
This is the code for my server - client program:
import getpass
from requests import get
import os
import thread
import socket
import sys
os.system('cls' if os.name == 'nt' else 'clear')
print '\033[91mMCP CONTROLLER\033[0m'
print ('--------------------------------------')
print ('Welcome back,' + getpass.getuser())
print ('--------------------------------------')
ip = get('https://api.ipify.org').text
print ('Your current external IP is: ' + ip)
print ('--------------------------------------')
HOST = 'localhost'
PORT = 1979
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'lul'
sys.exit()
print 'Socket bind complete'
s.listen(20)
print 'Listening...'
while 1:
conn, addr = s.accept()
print 'Client connected: ' + addr[0] + ':' + str(addr[1])
msg = conn.recv(1024)
print (msg)
s.close()
print ('Please enter command')
My problem is: I want the program to stop the socket after 20 seconds and do "print('Please enter command')" whether someone connects to it or not. If I start the program now it just says "Listening..." (if I don't start the client) forever and the only option I have is to close the terminal window. But I want the program to move on after 20 seconds.
And I also want it to say some special message if it didn't get any connection after 20 seconds (like print 'no client available')
Please pardon my bad english.
As #abarnet mentioned, settimeout is probably what you want, here is an example:
import getpass
from requests import get
import os
import thread
import socket
import sys
import time
os.system('cls' if os.name == 'nt' else 'clear')
print('\033[91mMCP CONTROLLER\033[0m')
print ('--------------------------------------')
print ('Welcome back,' + getpass.getuser())
print ('--------------------------------------')
ip = get('https://api.ipify.org').text
print ('Your current external IP is: ' + ip)
print ('--------------------------------------')
HOST = 'localhost'
PORT = 1979
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created!')
try:
s.bind((HOST, PORT))
except socket.error as msg:
print( 'lul')
sys.exit()
print( 'Socket bind complete')
s.settimeout(5)
s.listen(20)
print ('Listening...')
while 1:
try:
conn, addr = s.accept()
msg = conn.recv(1024)
print (msg)
except socket.timeout as e:
print(e,': no connections after 5 seconds...')
s.close()
break
print( 'Client connected: ' + addr[0] + ':' + str(addr[1]))
print('please enter command:')
Use the socket.settimeout ()
s.settimeout (20);

Python multithreaded TCP socket server in python

I am learning how to create multithreaded socket server in Python. I used example from some site that I don't remember. I am trying to create simple plugin system but I am not successful. It says that I am passing 3 arguments instead of 2. This is my code:
def handler(clientsock,addr):
while 1:
data = clientsock.recv(BUFF)
if not data: break
data_sanitized = data.rstrip()
print repr(addr) + ' received: ' + repr(data_sanitized)
from plugins.helloWorld import helloWorld
clazz.fireIt(clientsock,data)#HERE IS THE PROBLEM I THINK
if "close" == data.rstrip(): break
clientsock.close()
print addr, "CLIENT CLOSED CONNECTION"
if __name__=='__main__':
ADDR = (HOST, PORT)
serversock = socket(AF_INET, SOCK_STREAM)
serversock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serversock.bind(ADDR)
print 'STARTED SERVER, WAITING FOR CONNECTIONS', PORT
serversock.listen(5)
while 1:
clientsock, addr = serversock.accept()
print 'INCOMING CONNECTION FROM: ', addr
thread.start_new_thread(handler, (clientsock, adde))
and this is my plugin:
from socket import *
def response(key):
return '<response>' + key + '</response>'
class helloWorld():
def fireIt(clientsock,data):
print clientsock
clientsock.send(response(data))
print 'SENDING: ' + repr(response(data))
Thank you

Raspberry pi python server not sending serial read/write commands

I've got two servers (written in python) that are nearly identical in the way they handle serial communications on the Pi. However, one works and the other one doesn't and I can't seem to find the problem. I've hooked up a logic analyzer and the first server triggers the rx/tx properly when communicating serially, however, the second server will not trigger anything.
First (working) server - cut down to show only the serial:
import socket
import sys
import RPi.GPIO as GPIO
from serial import Serial
#HOST = ' ' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privleged port
ser = 0
#accepts a command as a string, parameters separated by white space
def processData( data ):
print ( "cmd : " + data).strip()
parseData = data.split(" ")
cmdLength = len(parseData)
cmd = parseData[0]
if cmd == "digitalWritePin":
pin = parseData[1]
state = parseData[2]
#GPIO.setup(pin, GPIO.OUT) # SHOULD HAVE ALREADY BEEN DONE W/ A CONFIG!!!
if state == '1':
GPIO.output(int(pin), True)
elif state == "0":
GPIO.output(int(pin), False)
elif cmd == "serialConfig":
baudRate = int(parseData[1])
timeOut = int(parseData[2])
global ser
ser = Serial('/dev/ttyAMA0', baudRate, timeout=timeOut)
elif cmd == "serialWrite":
serialcmd = parseData[1]
writeBuff = data.split("serialWrite")
#print writeBuff[1].strip(" ")
ser.write(writeBuff[1].strip(" "))
elif cmd == "serialReadLine":
print "serial read:"
response = ser.readline()
print response
conn.sendall(response)
print "read done"
return
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.bind((HOST,PORT))
print 'Socket bind complete'
s.listen(10) #parameter: backlog, controls number of connections that are 'queued'
print 'Socket now listening'
#Function f or handling connections. this will be used to create threads
def clientthread(conn):
#sending message to connected client
try:
while True:
data = conn.recv(1024)
if not data:
break
processData( data )
#out of the loop
conn.close()
except socket.error , msg:
print 'Recv failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run
#second is the tuple of arguments to the function
start_new_thread(clientthread,(conn,))
s.close
the most important parts of that being:
ser = Serial('/dev/ttyAMA0', baudRate, timeout=timeOut)
and the serial config/read/write areas of the el/if block
and the second sever (that is not working):
import socket
import sys
from time import sleep
from serial import Serial
from thread import *
import binascii
#HOST = ' ' # Symbolic name meaning all available interfaces
HOST = '10.1.10.28'
PORT = 8889 # Arbitrary non-privleged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST,PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10) #parameter: backlog, controls number of connections that are 'queued'
print 'Socket now listening'
ser = Serial('/dev/ttyAMA0', baudrate = 115200, timeout= 10)
#ser.open #--- uncommenting this does not make a difference
#Function f or handling connections. this will be used to create threads
def clientthread(conn):
#infinite loop so the function does not terminate and thread does not end
try:
while True:
print "step 1"
first = conn.recv(1)
print "step 2"
if not first:
break
hextFirst = hex( ord(first) )
print hextFirst
if hextFirst == '0xff':
print "step 3"
#ser.write(hextFirst) #send 0xff (converted)
ser.write(first) #send 0xff (orignal)
length = conn.recv(1) #get length
hextLength = hex( ord(length) ) #convert length
intlength = ord(length)
print "hextLength: " + hextLength
print "step 4"
#ser.write(hextLength) #send length (converted)
ser.write(length) #send length (original)
cmd = 0
if ord(length) == 0:
cmd = conn.recv(13)
else:
cmd = conn.recv(ord(length)-2)
hextCmd = binascii.b2a_hex(cmd)
print cmd
print "hextCmd: " + hextCmd
#ser.write(hextCmd) #send cmd (converted)
ser.write(cmd) #send cmd (original)
#sleep(1)
response = ser.read(1) #get response
#hextResponse = hex(ord(response))
print "serial resp: " + response
conn.sendall(response) #send response to LV
print "step 5"
print "step 6"
sleep(10)
#out of the loop
conn.close()
except socket.error , msg:
print 'Recv failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
try:
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run
#second is the tuple of arguments to the function
start_new_thread(clientthread,(conn,))
s.close
except KeyboardInterrupt:
ser.close
s.close
print "Exiting: Keyboard Interrupt"
I realize that is alot of code to go through, but you can ignore most of it, i'm just wondering what went wrong in the serial config/write. Like i said initially, the problem comes from the logic analyzer not seeing any serial communications (to or from) on the 2nd server, while the first server is working just fine
Try releasing /dev/ttyAMA0 from the default console by editing /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 kgdboc=ttyAMA0,115200 console=tty1 ..
change it to
dwc_otg.lpm_enable=0 console=tty1 .....
and removing this line from /etc/inittab
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
also make sure you run the program as super user sudo

Categories