As part of a uni course, I have to write a simple python TCP client-server chat but I'm having issues getting the sockets in the server.py and client.py programs to connect.
After many attempts I decided to really strip back the program to just try to connect the sockets and have the client send one message to the server after they are connected.
I am running the two programs (server.py and client.py) on the same computer (macOS) in separate terminal windows. I have tried turning off the firewall and running the programs as well just in case that was somehow causing an issue.
My code is as below:
server.py - This is run first
from socket import *
serverPort = 11500
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
print("The server is listening")
serverSocket.listen(1)
clientSocket, clientAddress = serverSocket.accept()
message, clientAddress = serverSocket.recvfrom(2048)
client.py - Once server.py is running, this is then started
from socket import *
serverName = "127.0.0.1"
serverPort = 11500
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
message = "Hello"
clientSocket.send(message.encode())
This is the error I have been receiving:
(base) me#ME python_socket % python3 tcp_server.py
The server is listening
Traceback (most recent call last):
File "tcp_server.py", line 11, in <module>
message, clientAddress = serverSocket.recvfrom(2048)
OSError: [Errno 57] Socket is not connected
Thanks in advance for any help. It seems like something that should be really simple but even after watching tutorials online I still seem to have the issue of the sockets not connecting.
Problems
You should use recv() instead of recvfrom() when you connect using TCP. recvfrom() is used for UDP socket.
Instead of receiving data from serverSocket, you should use newly created TCP clientSocket.
Correct Solution
Server
from socket import *
serverPort = 11500
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("localhost", serverPort))
print("The server is listening")
serverSocket.listen(1)
clientSocket, clientAddress = serverSocket.accept()
message = clientSocket.recv(2048).decode()
print(message)
Client
from socket import *
serverName = "127.0.0.1"
serverPort = 11500
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
message = "Hello"
clientSocket.send(message.encode())
Server Output:
The server is listening
Hello
The issue is that, in the server.py code, you should replace serverSocket in the recvfrom line with clientSocket, since when you call accept right before that line, clientSocket (returned by accept) is a new socket specific to that connection.
clientSocket, clientAddress = serverSocket.accept()
message, clientAddress = clientSocket.recvfrom(2048)
After that change, it is going to work just fine.
Related
I have an assignment where I have to write TCP client server python programs to implement a basic voting application. There are only two candidates: JohnD and JaneD. I was testing the communication between the client and server. So when I run the client side, nothing happens. Could someone tell me why.
At first I was using "localhost" for serverName but I kept getting this error: clientSocket.connect(("localhost", serverPort))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
So I set the serverName to my local IP. The client runs but nothing happens.
#TCP CLIENT#
from socket import*
#serverName = "localhost"
serverName = "131.100.39.41"
serverPort = 9001
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(("131.100.39.41", serverPort))
option = input("Enter the voter name: ")
clientSocket.send(bytes(option, "utf-8"))
print("Name sent to server.", option)
clientSocket.close()
This is the server side.
#TCP SERVER#
from socket import*
serverPort = 9001
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(("", serverPort))
serverSocket.listen(1)
print("Server is up and running.")
while(1):
connectionSocket, addr = serverSocket.accept()
option = connectionSocket.recv(1024)
print("received from client", option)
serverSocket.close()
This code looks good. It is working.
You get connectionRefused error in client , because the PORT is not opened , or there is 2 channels opened for the port. The port is opened for listening only when the server is started.
check with 'netstat -anp | findstr ":9001"
If there is port already opened , then choose another port or kill the port.
Remember:
Change your socket back to localhost or 127.0.0.1
First Start the server and then start the client
below is output i recieved , when i ran your code
Server
Server is up and running.
received from client b'test'
client:
Enter the voter name: test
Name sent to server. test
I'm new to how networking works and I'm trying to write two scripts for a class assignment, one acts as a server and one as a client. Both the server and client scripts are to be run on the same computer and each one uses two different ports (client port and server port). The client should be able to send a message to the server and then get a message back if the send was successful. This is the client code:
from socket import *
serverName = 'hostname'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()
And this is the server code:
from socket import *
serverPort = 2000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print("The server is ready to receive")
while True:
message, clientAddress = serverSocket.recvfrom(3000)
modifiedMessage = message.decode().upper()
serverSocket.sendto(modifiedMessage.encode(), clientAddress)
The server code runs fine but I get this error from running the client code:
socket.gaierror: [Erno 11001] getaddrinfo failed
Specifically, it doesn't like
clientSocket.sendto(message.encode(), (serverName, serverPort)
I saw multiple threads on here about this error but none of them really helped with my issue. I already checked to ensure both the ports are definitely open before executing both scripts, and they are. My initial guess is that it can't find the actual server port, even though it's up and running and waiting for a response. So I'm stumped. What does this error mean and how can I resolve this?
You forgot to actually connect the client socket to the server socket before trying to send a message:
from socket import *
serverName = 'localhost'
serverPort = 2000
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.connect((serverName, serverPort))
message = input('Input lowercase sentence:')
clientSocket.sendto(message.encode(), (serverName, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(3000)
print(modifiedMessage.decode())
clientSocket.close()
I also changed the serverName to localhost.
In the first part of this assignment you are going to implement an echo server which receives text message from client and sends it back to the client. (That’s why we call it echo server) When the server receives the text message from client, it capitalizes the odd characters of the text message. For example, when the client sends a text message of “hello elec 4120 student”, the server should return a text message of “HeLlO ElEc 4120 StUdEnT”.
With some hints from the instructor, my server code is as follow
from socket import *
serverPort = 12000
#create TCP welcoming socket
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
#server begins listening for incoming TCP requests
serverSocket.listen(1)
print('The server is ready to receive')
while True:
#server waits on accept()
#for incoming requests, new socket created on return
connectionSocket, addr = serverSocket.accept()
#read bytes from socket (but not address as in UDP)
sentence = connectionSocket.recv(1024).decode()
capitalizedSentence = sentence.upper()
#close connection to this client (but not welcoming socket)
connectionSocket.send(capitalizedSentence.encode())
connectionSocket.close()
and the client code is
from socket import *
serverPort = 12000
serverName = 'localhost'
#create TCP socket for server, remote port 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input('Input lowercase sentence:')
#No need to attach server name, port
clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print ('From Server:', modifiedSentence.decode())
clientSocket.close()
and when I run the server code
'The server is ready to receive'
is shown but when I run the client part,
line 6, in <module>
clientSocket.connect((serverName,serverPort))
ConnectionRefusedError: [Errno 61] Connection refused
is shown
I have been trying to send broadcast message for a long time but unable to receive it at all from the other side and no error at all. Server side it quickly sends packet and client keeps listening but never prints. Please answer me if someone really did this. I am using two virtual machines of same linux ubuntu. One for server and other for client.
#client
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("192.168.1.255",12345))
print s.recvfrom(4096)[0]
#server
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto("hi i am server!", ("<broadcast>", 12345))
I solved it myself.
Server side:
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.sendto("hi i am server!", ("192.168.1.255", 12345))
Client side:
from socket import *
s = socket(AF_INET, SOCK_DGRAM)
s.bind(("192.168.1.255",12345))
print s.recvfrom(4096)[0]
Instead of using "<broadcast>" as an address we should use the same subnet address
I am setting up a basic python application that will listen for UDP packets at a specific port.
I am using an example code found online to begin to familiarize myself with UDP and socket connection.
When I invoke client.py and then server.py - the server does not respond and the terminal remains idle - any solutions for this problem? Below is the basic code I am working with
Client.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
Message = b"Hello, Server"
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientSock.sendto(Message, (UDP_IP_ADDRESS, UDP_PORT_NO))
Server.py
import socket
UDP_IP_ADDRESS = "127.0.0.1"
UDP_PORT_NO = 6789
serverSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
while True:
#data, addr = serverSock.recvfrom(1024)
data, addr = serverSock.recvfrom(1024)
print ("Message: ", data)
When I invoke client.py and then server.py
Well that's your problem--by invoking the client which sends, then later invoking the server which receives, you are preventing the two from communicating. The server needs to be running at the moment the client sends.