Recieved [Error data].. Socket programming in python - python

I amusing a client to send a message to a python server.
client side: client.send("1")
Server side:
d=clientsocket.recv(1024)
if (d=="1"):
print(" Correct value")
It won't print correct value. I know the error at recv as I don't know how it works. Could anyone please help me to solve this matter.

You just need simple modification to work it correctly:-
in client correct like below:-
client.send("1".encode())
in server correct like below:-
d=clientsocket.recv(1024).decode()
if (d=="1"):
print(" Correct value")
I have created one client and server for you which is working fine in Python 3.4. Please try and check:
Here is your server
import socket
import sys
HOST = "localhost"
PORT = 8000
print("Creating socket...")
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Binding socket...")
try:
sc.bind((HOST, PORT))
except socket.error as err:
print("Error binding socket, {}, {}".format(err[0], err[1]))
print("bound Successful")
# Configure below how many client you want that server can listen to simultaneously
sc.listen(2)
print("Server is listening on {}:{}".format(HOST, PORT))
while True:
conn, addr = sc.accept()
print("Connection from: " + str(addr))
print("Receiving data from client\n")
data = conn.recv(1024).decode()
print("Client says :" + data)
if(data == "2"):
print(" Ooh you are killing me with value :" + data)
conn.sendall(str.encode("\n I am server and you killed me with :" + data))
break;
elif(data == "1"):
print(" Correct value :" + data)
conn.sendall(str.encode("\n I am server and you hit me with correct value:" + data))
else:
print(" You are sending a wrong value :" + data)
conn.sendall(str.encode("\n I am server and you hit me with wrong value :" + data))
sc.close()
and now your client is here:-
import socket
import sys
HOST = "localhost"
PORT = 8000
print("creating socket")
sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Connecting to host")
try:
sc.connect((HOST, PORT))
except socket.error as err:
print("Error: could not connect to host, {}, {}".format(err[0], err[1]))
sys.exit()
print("Connection established to host")
message = "1" # Run client 3 times with value message = '1' and '5' and '2'
sc.send(message.encode())
data = sc.recv(1024).decode()
print("Server response is : " + data)
sc.close()

Related

Not able to execute the program successfully, gives "Error: Address already in use"

I am working on Networking module,making connections with client ans server.
The Server code is as follows :
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.connect()
print "Connection from: " + str(addr)
while True:
data = c.recv(1024)
if not data:
break
print "from connected user: " + str(data)
data = str(data).upper()
print "sending: " + str(data)
c.send(data)
c.close()
if __name__ == '__main__':
Main()
The Client code is as follows:
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
data = s.recv(1024)
print 'Received from server: ' + str(data)
message = raw_input("-> ")
s.close()
if __name__ == '__main__':
Main()
But not able to execute the program successfully, gives the error address already in use.
Use the command netstat -nlp and find out the above mentioned port in the list.You will find the same port and the corrosponding PID also, either kill that process by kill -9 or you can go to your respective code and change the port number.
Secondly,it's preferrable to use localhost instead of '127.0.0.1'.
And there's an issue in your server code as well, instead of this statement 'c, addr = s.connect()' you need to write this one ' c, addr = s.connect()'.You need too accept the incoming connection and then connect with it.You are missing the acceptance of incoming connection.

Python - Socket Communication, multiple messages

I'm stuck on this socket communication, I've looked everywhere but I haven't found an answer yet.
THE PROBLEM: I can only send 1 message from the client before it either gives me an error or ends the script.
I need to be able to send multiple messages to the server.
The server side (shown below) should be fine:
# Echo server program
import socket
import time
import os
#-----------------------------------------------------------------------------------------------------------------------
today = time.strftime('%Y.%m.%d')
logFileName = "log - " + today + ".txt"
HOST = '10.0.0.16'
PORT = 8080 # Reserve a port for your service
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create a socket object
s.bind((HOST, PORT)) # Bind to the port
def print_write(text):
log.write(time.strftime("%H:%M:%S") + " | " + text)
log.write("\n")
print text
#-----------------------------------------------------------------------------------------------------------------------
if os.path.isfile(logFileName) is True:
log = open(logFileName, 'a+')
print_write("[SERVER] Log for " + today + " already exists.")
print_write("[SERVER] Starting comms")
else:
print "[SERVER] Log doesn't exist"
log = open(logFileName, 'a+') # Create file -> log - %date%.txt
print_write("[SERVER] Log created")
while True:
s.listen(1)
conn, addr = s.accept()
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
log.close()
Sorry if it's very messy and confusing but i don't have much time to finish this project, if you have any question just ask.
For the client side I don't have much but here, I'll give you this:
import socket
HOST = '10.0.0.16' # The remote host
PORT = 8080 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while True:
msg = raw_input()
s.sendall(msg)
print msg
I know it doesn't work, it's just to give you an idea of what I need.
Thank you in advance.
The problem is, that you only read the first message from each open connection before moving on to the next. The accept() methods waits for a new connection and gives you the information needed when a new one comes in. the recv() method on the other hand, receives data from a existing connection and waits if there is none. If you want to receive multiple messages from a single client, you can just wait for the first connection and then wait for data with recv(). This could look like this:
s.listen(1)
conn, addr = s.accept()
while True:
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
If you want to be able to also manage multiple clients, you will have to create a thread for each one from a while loop waiting for new connections. This is a bit more complicated:
def client_handler(conn):
while True:
data = conn.recv(BUFFER_SIZE)
if data == "Comms Shutdown":
print_write("------ REMOTE SHUTDOWN ------")
conn.close()
raise SystemExit
# this will kill the server (remove the line above if you don't want that)
else:
print_write("[COMMS] " + str(addr) + " says: " + data)
while True:
s.listen(1)
conn, addr = s.accept()
recv_thread = threading.Thread(target=client_handler, args=(conn, ))
recv_thread.start()
All this code is untested. Be aware, that I omitted the logging part and the socket creation part as well as all imports.

Python simple socket chat User connection and output of message

I am creating a simple chat in python 3 using socket
here are the code
CLIENT
#!/bin/python
import socket
import threading
import time
tLock = threading.Lock()
poweroff = False
def receving(name, sock):
while not poweroff:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
print (str(data))
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1', 5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread", s))
rT.start()
alias = input("Username: ")
time.sleep(0.2)
message = input(alias + ">>> ")
while message != 'q':
if message != "":
s.sendto(str(alias + ": " + message).encode('utf-8'), server)
tLock.acquire()
message = input(alias + ">>> ")
tLock.release()
time.sleep(0.2)
poweroff = True
rT.join()
s.close()
SERVER
#!/bin/python
import socket
import time
hostname = '127.0.0.1'
port = 5000
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((hostname, port))
s.setblocking(0)
iQuit = False
print ("Server Started.")
while not iQuit:
try:
data, addr = s.recvfrom(1024)
if addr not in clients:
clients.append(addr)
print (time.ctime(time.time()) + str(addr) + ": :" + str(data))
for client in clients:
s.sendto(data, client)
except:
pass
s.close()
How do i print a string to the server when a user connect?
I have tried to add this string after you have insert the name
s.sendto(str(alias + " Connected").encode('utf-8'), server)
but the output is orrible for me
Another Question:
Why i get something like this when seding a message?
Username: User_A
User_A>>> Hello
User_A>>> How Are you?
b'User:A: Hello'
User_A>>>
b'User_A: How Are you?'
b'User_B: Hi'
Concerning your second question: You are printing binary strings, see here for more information.
Use str(data.decode('utf-8')) instead of str(data) when printing the message on the server or the client.
Concerning the first question: This should work if you send the "Connected" string just after asking for the user name.
The string is decoded the same way as a common message if you include the decode('utf-8') and looks normal to me.
i have to press enter to see if user_B send something to me.
You enforced this behavior by locking out the receiving thread during the input of a message. You have to make up your mind whether you want this or want incoming data to be printed while typing.
You might want to cf. Simultaneous input and output for network based messaging program.

Python socket: Bad File Descriptor for simple client connection script

My script is very simple.
1.) Server listens for an HTTP connection
2.) Client establishes connection
3.) Server prints our the client's HTTP request data
When a client connects to the server and makes a browser request it triggers the Socket error "Bad File Descriptor".
I'm not sure why it does this. Can anyone help me out?
import socket
host = ''
port = 1000
def proxy(connection,client):
request = connection.recv(MAX_DATA_RECV)
print request
connection.close()
def main():
try:
# create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# associate the socket to host and port
s.bind((host, port))
# listenning
s.listen(BACKLOG)
print("Listening for connections")
except socket.error, (value, message):
if s:
s.close()
print "Could not open socket:", message
# get the connection from client
while 1:
try:
conn, client_addr = s.accept()
print("Received connection from " + str(client_addr))
proxy(conn,client_addr)
#thread.start_new_thread(proxy, (conn,client_addr))
if s:
s.close()
except socket.error, (value,message):
print value
print message
sys.exit(1)
main()
You are closing the server socket after first client. Don't do this.
while True:
try:
conn, client_addr = s.accept()
print("Received connection from " + str(client_addr))
proxy(conn,client_addr)
except socket.error, (value,message):
print value
print message

Encoded Communication

I'm trying to learn Network programming with Python language. In order that, I created a simple chat program with python. Now I want to encrypt communication between Server and Clients. How can I do that? The following code is my server code:
TcpSocket.bind(("0.0.0.0",8000))
TcpSocket.listen(2)
print("I'm waiting for a connection...!")
(client, (ip, port)) = TcpSocket.accept()
print("Connection recived from the {}".format(ip))
messageToClient = "You connected to the server sucessfuly.\n"
client.send(messageToClient.encode('ascii'))
dataRecived = "Message!"
while True:
dataRecived = client.recv(1024)
print("Client :", dataRecived)
print("Server :")
dataSend = raw_input()
client.send(str(dataSend) + "\n")
print("Connection has been closed.")
client.close()
print("Server has been shutdowned.")
TcpSocket.close()
def main():
try:
print("Server has started.")
connectionOrianted()
except :
print("Maybe connection terminated.")
finally:
print("Session has closed.")
if __name__ == "__main__": main()
And the following code is my client code.
#!/usr/bin/python3
import socket
import sys
from builtins import input
def main():
try:
serverHostNumber = input("Please enter the ip address of the server: \n")
serverPortNumber = input("Please enter the port of the server: \n")
# create a socket object
TcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connection to hostname on the port.
TcpSocket.connect((serverHostNumber, int(serverPortNumber)))
while True:
data = TcpSocket.recv(1024)
print("Server : ", data)
sendData = input("Client : ")
if sendData == "exit":
TcpSocket.close()
sys.exit()
TcpSocket.send(sendData.encode(encoding='ascii', errors='strict'))
except Exception as e:
print("The error: ", e)
TcpSocket.close()
sys.exit()
if __name__ == "__main__" : main()
I'm assuming you want to use the defacto standard for network encryption SSL (Secure Sockets Layer).
Client side is easy, basically you wrap your standard socket with an SSL socket, client side is built in so there's nothing special to install or import.
#!/usr/bin/python3
import socket
import sys
from builtins import input
def main():
try:
serverHostNumber = input("Please enter the ip address of the server: \n")
serverPortNumber = input("Please enter the port of the server: \n")
# create a socket object
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connection to hostname on the port.
sock.connect((serverHostNumber, int(serverPortNumber)))
TcpSocket = socket.ssl(sock)
while True:
data = TcpSocket.recv(1024)
print("Server : ", data)
sendData = input("Client : ")
if sendData == "exit":
TcpSocket.close()
sys.exit()
TcpSocket.send(sendData.encode(encoding='ascii', errors='strict'))
except Exception as e:
print("The error: ", e)
sys.exit()
if __name__ == "__main__" : main()
Server side is more difficult.
First you will need to install pyopenssl
After that you will need to generate a private key and a certificate (unless you already have one), this is pretty straight forward on linux, just run this from the command line:
openssl genrsa 1024 > key
openssl req -new -x509 -nodes -sha1 -days 365 -key key > cert
For Windows you will need to use one of these methods
Finally, once all the prerequisites are done SSl wraps sockets for the server side much like it does for the client side.
import socket
from OpenSSL import SSL
context = SSL.Context(SSL.SSLv23_METHOD)
context.use_privatekey_file('key')
context.use_certificate_file('cert')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = SSL.Connection(context, s)
s.bind(("0.0.0.0",8000))
s.listen(2)
print("I'm waiting for a connection...!")
(client, (ip, port)) = s.accept()
print("Connection recived from the {}".format(ip))
messageToClient = "You connected to the server sucessfuly.\n"
client.send(messageToClient.encode('ascii'))
dataRecived = "Message!"
while True:
dataRecived = client.recv(1024)
print("Client :", dataRecived)
print("Server :")
dataSend = raw_input()
client.send(str(dataSend) + "\n")
print("Connection has been closed.")
client.close()
print("Server has been shutdowned.")
s.close()
def main():
try:
print("Server has started.")
connectionOrianted()
except :
print("Maybe connection terminated.")
finally:
print("Session has closed.")
I haven't had the chance to test these scripts, but they should work. I hope this answers your question.

Categories

Resources