-2

I try this code:

server:

import socket

s=socket.socket()

ip='localhost'
port=9999
s.bind((ip,port))
s.listen()
print("wait for client...")
c,addr=s.accept()
print("client added!")
while True:
    msg=input("your masage:>>>")
    c.send(msg.encode())
    print(c.recv(1000000).decode())

client:

import socket

s=socket.socket()

ip='localhost'
port=9999

s.connect((ip,port))
print("connected")
while True:
    print(s.recv(1000000).decode())
    msg=input("your masage:>>>")
    s.send(msg.encode())

and I get this error in the client:

Traceback (most recent call last):
  File "F:\chat room\client\chat room-client.py", line 8, in <module>
    s.connect((ip,port))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

I try this on 2 computers and I was getting error but when I try this on 1 computer I don't get any error and the program work.

(please write code for answer)

  • 3
    In your own words, when you set `ip='localhost'`, what do you think that means? When you want the client to connect to the server, and those are two separate computers, what is your plan for telling the client *which* computer the server is on? Do you know what an IP address is? – Karl Knechtel Aug 13 '21 at 10:04
  • Is this `ip='localhost'`just for the purpose of the question? This variable has to have the ip addresses of the target machines. – Tony Aug 13 '21 at 10:18

1 Answers1

2

You're pointing to localhost in both server and client sides. Assuming you are in a local network, you should first expose you server in '0.0.0.0' IP, so it can be seen externally to the host machine. Then, you need to know the local ip address of the server machine within the local network, and to use it as IP in the client side.

server:

import socket

s=socket.socket()

ip='0.0.0.0'
...

client:

import socket

s=socket.socket()

ip='YOUR-SERVER-MACHINE-LAN-IP' # You can obtain this IP with ipconfig (windows) or ifconfig (linux), usually like 192.168.x.x
...
jalm
  • 56
  • 1
  • 4