how to use ping/pong for checking the message is delivered to server or not and receive a pong after sucessfull delivery of message in the below code.
I found this code from this link
https://www.positronx.io/create-socket-server-with-multiple-clients-in-python/
server-side.py
import socket
from _thread import *
ServerSideSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ServerSideSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = '127.0.0.1'
port = 3040
ThreadCount = 0
try:
ServerSideSocket.bind((host, port))
except socket.error as e:
print(str(e))
print('Socket is listening..')
ServerSideSocket.listen(5)
def multi_threaded_client(connection):
connection.send(str.encode('Server is working:'))
while True:
data = connection.recv(2048)
print(data)
response = 'Server message: ' + data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(response))
connection.close()
while True:
Client, address = ServerSideSocket.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(multi_threaded_client, (Client, ))
ThreadCount += 1
print('Thread Number: ' + str(ThreadCount))
ServerSideSocket.close()
client-side.py
import socket
ClientMultiSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '172.0.0.1'
port = 3040
print('Waiting for connection response')
try:
ClientMultiSocket.connect((host, port))
except socket.error as e:
print(str(e))
res = ClientMultiSocket.recv(1024)
while True:
Input = input('Hey there: ')
ClientMultiSocket.send(str.encode(Input))
res = ClientMultiSocket.recv(1024)
print(res.decode('utf-8'))
ClientMultiSocket.close()
Related
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()
I'm trying to have multiple clients connect to a server socket and transfer data between them, however I want to limit the number of connections that can be made to the server/ number of client processes to 3. How can I do this?
server:
import socket
from _thread import *
PORT = 5050
HOST = socket.gethostbyname(socket.gethostname())
ADDR = (HOST, PORT)
ThreadCount = 0
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp.bind(ADDR)
except socket.error as e:
print(str(e))
print("Awaiting connection")
tcp.listen(5)
def threaded_client(connection):
connection.send(str.encode('Welcome to sv'))
while True:
data = connection.recv(2048)
reply = 'Server returns: ' + data.decode('utf-8')
if not data:
break
connection.sendall(str.encode(reply))
connection.close()
while True:
Client, address = tcp.accept()
print('Connected to: ' + address[0] + ':' + str(address[1]))
start_new_thread(threaded_client, (Client, ))
ThreadCount += 1
print('Number of threads: ' + str(ThreadCount))
ServerSocket.close()
client:
import socket
Client = socket.socket(socket.AF_INET, socket. SOCK_STREAM)
PORT = 5050
HOST = socket.gethostbyname(socket.gethostname())
ADDR = (HOST, PORT)
print('Awaiting connection')
try:
Client.connect(ADDR)
except socket.error as e:
print(str(e))
Response = Client.recv(1024)
while True:
Input = input('Sends Info: ')
Client.send(str.encode(Input))
Response = Client.recv(1024)
print(Response.decode('utf-8'))
Cliente.close()
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()
I have written a telnet server and client, but I don't receive a response from the server and I don't know where the problem is.
SERVER
import socket
import subprocess
def handle_client(client_socket):
MAX_RECV_BUFFER = 1024
allowed_commands = ["ls, cd, ls -l"]
recv_size = 1
while recv_size:
data_buffer = client_socket.recv(MAX_RECV_BUFFER)
command = data_buffer.decode("utf-8")
if not data_buffer:
print("Client just disconected")
break
recv_size = len(data_buffer)
if command in allowed_commands:
response = run_command(commad)
client_socket.send(response.encode("utf-8"))
data_buffer = ""
def init_server(server_address, reuseAddr=True):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
server_socket.bind(server_address)
except socket.error as serr:
print(str(serr))
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server_socket.listen(5)
print("Server listen at {}:{}".format(server_address[0], server_address[1]))
try:
while True:
client_socket, client_address = server_socket.accept()
print("Client has connected {}:{}".format(client_address[0], client_address[1]))
handle_client(client_socket)
except KeyboardInterrupt as kerr:
print("Server is closing...")
client_socket.close()
server_socket.close()
def run_command(commad):
try:
output = subprocess.check_output(commad, stderr=subprocess.STDOUT,
shell=True)
except OSError as oserr:
return output
if __name__ == "__main__":
init_server(("127.0.0.1",8080))
CLIENT
import socket
def init_client(server_address):
connected = True
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Connecting {} to server ...'.format(server_address))
client_socket.connect(server_address)
while connected:
# allowed__commands = ['ls, cd, ls-l']
try:
if server_address[0] == '127.0.0.1':
message = input('\nlocalhost#localhost' + '>> ')
else:
message = input(server_address[0] + '#' + server_address[1] +
'>> \n')
print('Sending message: {}'.format(message))
client_socket.sendall(message.encode('utf-8'))
recv_data(client_socket)
except IOError as e:
print('Error: {}'.format(e))
except Exception as e:
print('Other error: {}'.format(e))
except KeyboardInterrupt:
connected = False
def recv_data(client_socket):
recv_size = 1
MAX_RECV_BUFFER = 1024
while recv_size:
data_buffer = client_socket.recv(MAX_RECV_BUFFER)
message = data_buffer.decode('utf-8')
print('Received data: '.format(message))
if not data_buffer:
break
recv_size += len(data_buffer)
data_buffer = ''
client_socket.close()
if __name__ == '__main__':
init_client(('127.0.0.1', 8080))
I am making server-client communication in python using sockets and threading module. I connect client to server, send some data, receive some data, but the problem is, I can send only two messages. After those, the server is not reciving my packets. Can someone tell me what's wrong? Thanks in advance.
Server.py:
import socket
from threading import Thread
class Server:
def __init__(self):
self.host = '127.0.0.1'
self.port = 9999
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
self.threads = []
self.listen_for_clients()
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print('Accepted Connection from: '+str(addr[0])+':'+str(addr[1]))
self.threads.append(Thread(target=self.handle_client, args=(client, addr)))
for thread in self.threads:
thread.start()
def handle_client(self, client_socket, address):
client_socket.send('Welcome to server'.encode())
size = 1024
while True:
message = client_socket.recv(size)
if message.decode() == 'q^':
print('Received request for exit from: '+str(address[0])+':'+str(address[1]))
break
else:
print('Received: '+message.decode()+' from: '+str(address[0])+':'+str(address[1]))
client_socket.send('Received request for exit. Deleted from server threads'.encode())
client_socket.close()
if __name__=="__main__":
main = Server()
Client.py
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
while True:
data = input()
client.send(data.encode())
message = client.recv(4096)
print('[+] Received: '+ message.decode())
main()
You have to send exit message 'q^' to client too to close client.
Warning:
Using Unicode as encoding for string is not recommended in socket. A partial Unicode character may be received in server/client resulting in UnicodeDecodeError being raised.
Code for server using threads is:
server.py:
import socket
from threading import Thread
class Server:
def __init__(self, host, port):
self.host = host
self.port = port
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.bind((self.host, self.port))
self.server.listen(5)
def listen_for_clients(self):
print('Listening...')
while True:
client, addr = self.server.accept()
print(
'Accepted Connection from: ' + str(addr[0]) + ':' + str(addr[1])
)
Thread(target=self.handle_client, args=(client, addr)).start()
def handle_client(self, client_socket, address):
size = 1024
while True:
try:
data = client_socket.recv(size)
if 'q^' in data.decode():
print('Received request for exit from: ' + str(
address[0]) + ':' + str(address[1]))
break
else:
# send getting after receiving from client
client_socket.sendall('Welcome to server'.encode())
print('Received: ' + data.decode() + ' from: ' + str(
address[0]) + ':' + str(address[1]))
except socket.error:
client_socket.close()
return False
client_socket.sendall(
'Received request for exit. Deleted from server threads'.encode()
)
# send quit message to client too
client_socket.sendall(
'q^'.encode()
)
client_socket.close()
if __name__ == "__main__":
host = '127.0.0.1'
port = 9999
main = Server(host, port)
# start listening for clients
main.listen_for_clients()
client.py:
import socket
import sys, time
def main():
target_host = '127.0.0.1'
target_port = 9999
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print('Could not create a socket')
time.sleep(1)
sys.exit()
try:
client.connect((target_host, target_port))
except socket.error:
print('Could not connect to server')
time.sleep(1)
sys.exit()
online = True
while online:
data = input()
client.sendall(data.encode())
while True:
message = client.recv(4096)
if 'q^' in message.decode():
client.close()
online = False
break
print('[+] Received: ' + message.decode())
break # stop receiving
# start client
main()