I am writing a Bulletin Board as a client server program using socket programming. The server side code is as follows:
import time
from socketserver import *
from socketserver import BaseRequestHandler, TCPServer
SENDING_COOLDOWN = 0.3
BUFFER_SIZE = 4096
class EchoHandler(BaseRequestHandler):
postSwitch = False
content = ""
error_str = 'ERROR - Command not understood'
ok_str = 'OK'
input_buffer=[]
def send_str(self, string):
self.request.send(bytes('server: ' + string, encoding='utf-8'))
time.sleep(SENDING_COOLDOWN)
def recv_str(self):
post_msg = self.request.recv(BUFFER_SIZE)
return str(post_msg, encoding='utf-8')
def handle(self):
print('Got connection from', self.client_address)
while True:
# try:
msg = self.request.recv(BUFFER_SIZE)
if not msg:
break
msg_str = str(msg, encoding='utf-8')
print('msg_str is :', msg_str)
msg_pieces = msg_str.split()
if len(msg_pieces) >= 2:
self.send_str(self.error_str)
elif len(msg_pieces) == 1:
command = msg_pieces[0]
print('command is :', command)
if command in ['POST', 'READ', 'QUIT', '#']:
if command == 'POST':
in_post = True
while in_post:
post_msg_str = self.recv_str()
if post_msg_str[-1] == "#":
in_post = False
self.send_str(self.ok_str)
else:
print(f"added: {post_msg_str}")
self.content += "\n" + post_msg_str
elif command == 'READ':
# self.send_str('Welcome socket programming')
for line in self.content.strip().split("\n"):
self.send_str(f"{line}")
self.send_str('#')
elif command == 'QUIT':
self.send_str(self.ok_str)
else:
self.send_str(self.error_str)
elif len(msg_pieces) < 1:
self.send_str(self.error_str)
if __name__ == '__main__':
serv = TCPServer(('', 16011), EchoHandler)
serv.serve_forever()
And this is the code for the client side file:
from socket import *
serverName = '127.0.0.1'
serverPort = 16011
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
userInput = ""
modifiedSentence = ""
with socket(AF_INET, SOCK_STREAM) as clientSocket:
clientSocket.connect((serverName,serverPort))
while True:
# code for receiving the text from the server
userInput = input("client: ")
clientSocket.sendall(userInput.encode())
if userInput == "POST":
while userInput != "#":
userInput = input("client: ")
clientSocket.sendall(userInput.encode())
print(clientSocket.recv(1024).decode())
elif userInput == "READ":
readOutput = ""
while readOutput != "server: #":
readOutput = clientSocket.recv(1024).decode()
print (readOutput)
elif userInput == "QUIT":
print(clientSocket.recv(1024).decode())
break
As it can be seen in the client side app, the servername is 127.0.0.1 (local host's IP Address) and the port number is 16011. Then it runs perfectly.
However, when I change the servername and host to something like 122.180.0.1 and 1200, it does not work.
I don't understand why this gives error as the server can bind with any host:

I think there are a few misconceptions that I'll try to clear up.
Specifying
('', 16011)for the server address means that your listener should bind to port 16011 for all network interfaces on your machine. This includes the local loopback interface (at 127.0.0.1) as well as other network interfaces your machine might have (e.g. for the wifi network you're connected to or the network you're plugged into via an ethernet cable). I believe on windows you can view the network interfaces you have through the system information interface: see the image here.If you change the server address to something like
('122.180.0.1', 1200), that means that your server will now only be listening on port 1200 to requests destined for the IP address 122.180.0.1. This also generally means that your server machine has to have this IP address assigned to it and that the client machine has to be to reach the server machine on that network. If that machine is not reachable at that IP address, you'll see an error message like the one you're seeing.In order for the client to connect with the server, it needs to be able to reach the server machine at its specified IP but also needs to be trying to connect to the same port as the server is listening on. If the server is listening on
('122.180.0.1', 16011), but the client tries to connect to('122.180.0.1', 1200)it won't be able to find the server because it's looking at the wrong port. My guess is that this is the main reason your client can't connect to the server (it's trying to connect to the wrong port).Some additional reasons the server can't be reached could include because it is behind a firewall that's blocking traffic to that port, or because it's on a private network that the client isn't on, or that the ip address you're supplying isn't a valid IP address for the server. However, it looks like you're running these both locally on the same machine, so it's very unlikely either of these are the case (as long as you're not using using some kind of virtualization like docker to run them). If you are running on the same machine, you can just use the IP 127.0.0.1 (or the hostname localhost, which is equivalent) to rule out networking/IP issues.