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
Related
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.
I am trying to run a simple python script on the Cisco Packet Tracer for testing. The code is for opening a socket for a TCP connection with a client only to get a string, set it to uppercase and send the modified string back to the client.
The code below works well on my machine; however, when I try to run this very same code on a virtual server created on the Cisco Packet Tracer (programming interface on the server), it returns the error: NotImplementedError: socket is not yet implemented in Skulpt in file src/lib/socket.py on line 1
from socket import *
import sys
serverPort = 3125 # Defines the port this socket will be listening
# Opens the socket, AF_INET: IPv4 | SOCK_STREAM: TCP socket
serverSocket = socket(AF_INET, SOCK_STREAM)
# Assigns the serverPort to the server socket
serverSocket.bind(("", serverPort))
serverSocket.listen(1) # Listens to one connection on the "handshake socket"
print("The server is ready to serve...") # Prints the server is running
while True:
# Accepts the connection with the client
connectionSocket, clientAddress = serverSocket.accept()
# Receives the messagem from the client
message = connectionSocket.recv(2048)
# Closes the server if the message is "exit"
if message.decode() == "exit":
connectionSocket.close()
break
# Modifies the message to upper case
modifiedMessage = message.decode().upper()
# Sends the modified message to the client
connectionSocket.send(modifiedMessage.encode())
connectionSocket.close() # Closes the socket
serverSocket.close() # Closes the handshake socket
sys.exit()
I appreciate.
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.
Simple client - server app.
#Server use decode
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host,port))
s.listen(5)
while True:
c,addr = s.accept()
print("Got connection from " + str(addr))
ret_val = s.send("Thank you".encode('utf-8'))
print ("ret_val={}".format(ret_val))
c.close()
Client:
#client use decode
from socket import gethostname, socket
serSocket = socket()
server = gethostname()
port = 12345
serSocket.connect((server, port))
data = serSocket.recv(1024)
msg = data.decode('utf-8')
print("Returned Msg from server: <{}>".format(msg))
serSocket.close()
when the server tries to send the following exception occurred
Traceback (most recent call last):
Got connection from ('192.168.177.1', 49755)
File "C:/Users/Oren/PycharmProjects/CientServer/ServerSide/Server2.py", line 16, in <module>
ret_val = s.send("Thank you".encode('utf-8'))
OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
Process finished with exit code 1
As can be seen the client connects the server successfully.
But send fails.
What is the problem?
The problem is that you are sending on the listening socket, not on the connected socket. connect returns a new socket which is the one you must use for data transfer. The listening socket can never be used for sending or receiving data.
Change the send to this and your program will work fine:
ret_val = c.send("Thank you".encode('utf-8'))
(Note c.send, not s.send)