Python socket server not printing the received data? - python

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()

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()

How to apply ping-pong for TCP socket?

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()

How to limit number of connections to server socket

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()

Server Loop Using Python Sockets and Threading module

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()

How can I have multiple clients on a TCP Python Chat Server?

Any help on how I can get this to accept more than one client, and why it isn't at the moment? Thanks!
Also, is there anything I'm doing wrong with this code? I've been following mostly Python 2 tutorials because I can't find any for Python 3.4
Here is my Server code:
import socket
import time
import os
from threading import Thread
folderPath = "Chat Logs"
filePath = folderPath + "/" + str(time.strftime("%H-%M-%S_%d-%m-%Y")) + ".txt"
def clientHandler(c):
while True:
data = c.recv(1024)
if not data:
break
data = data.decode("UTF-8")
message = str(data[:data.index("§")])
nick = str(data[data.index("§")+1:])
print(nick + ": " + message)
saveChat(nick, message)
print(" Sending: " + data)
c.send(bytes(data, "UTF-8"))
c.close()
def saveChat(nick, message):
if not os.path.exists(folderPath):
os.makedirs(folderPath)
if not os.path.exists(filePath):
f = open(filePath, "a")
f.close()
f = open(filePath, "a")
f.write(nick + ": " + message + "\n")
f.close()
def Main():
host = str(socket.gethostbyname(socket.gethostname()))
port = 5000
print(host + ":" + str(port) + "\n")
Clients = int(input("Clients: "))
s = socket.socket()
s.bind((host, port))
s.listen(Clients)
for i in range(Clients):
c, addr = s.accept()
print("Connection from: " + str(addr))
Thread(target=clientHandler(c)).start()
s.close()
if __name__ == "__main__":
Main()
And here is my Client code:
import socket
def Main():
print("Send 'q' to exit\n")
address = str(input("ip:port -> "))
nick = input("nick: ")
try:
if address.index(":") != 0:
host = address[:address.index(":")]
port = int(address[address.index(":")+1:])
except ValueError:
host = address
port = 5000
s = socket.socket()
s.connect((host, port))
message = input("-> ")
while message != "q":
s.send(bytes(message + "ยง" + nick, "UTF-8"))
data = s.recv(1024)
data = data.decode("UTF-8")
data2 = data
messageServer = str(data[:data.index("ยง")])
nickServer = str(data[data.index("ยง")+1:])
if not data == data2:
print(nickServer + ": " + messageServer)
message = input("-> ")
s.close()
if __name__ == "__main__":
Main()
First of all, I found these tutorials very helpful: BinaryTides
Here is an example of a simple tcp server that accepts multiple clients. All this one does receive data from the client and return "OK .. " + the_data. However, you could easily modify it to have a function that broadcasts the data(chat msg) to all clients connected. This example uses threading. You should google for the select module. With regards to your threads, are you sure you are a) using the right module/method for the job and b) that you are calling it in the right way?
import socket
import sys
from thread import start_new_thread
HOST = '' # all availabe interfaces
PORT = 9999 # arbitrary non privileged port
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print("Could not create socket. Error Code: ", str(msg[0]), "Error: ", msg[1])
sys.exit(0)
print("[-] Socket Created")
# bind socket
try:
s.bind((HOST, PORT))
print("[-] Socket Bound to port " + str(PORT))
except socket.error, msg:
print("Bind Failed. Error Code: {} Error: {}".format(str(msg[0]), msg[1]))
sys.exit()
s.listen(10)
print("Listening...")
# The code below is what you're looking for ############
def client_thread(conn):
conn.send("Welcome to the Server. Type messages and press enter to send.\n")
while True:
data = conn.recv(1024)
if not data:
break
reply = "OK . . " + data
conn.sendall(reply)
conn.close()
while True:
# blocking call, waits to accept a connection
conn, addr = s.accept()
print("[-] Connected to " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn,))
s.close()

Categories