-1

Hi there i was try to connect a client and a server using python socket... both the sides(client and server) are working without any error... Problem : When I try to connect the client to the server it gives the following error.

Traceback (most recent call last):
  File "tcpclient.py", line 8, in <module>
    client.connect((hos,po))
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused

I tried listening the port using netcat... And it worked Here is my code

Server :

mport socket
import threading

ip = "0.0.0.0"
po = 9999

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

server.listen(5)

print "[*] Listining on %s:%d" %(ip,po)

def handle_client(client_socket):
        request = client_socket.recv(1024)
        print "[*] Received: %s" % request
        client_socket.close()

while True :
        client,addr = server.accept()
        print "[*] Accepted connection from %s:%d" %(addr[0],addr[1])
        client_handler = threading.Thread(target=handle_client,args=(client,))
        client_handler.start()

Client :

import socket

hos =  "127.0.0.1"
po = 9999

client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

client.connect((hos,po))

client.send("Hello")

re = client.recv(3456)
print re
Cœur
  • 37,241
  • 25
  • 195
  • 267
4bh1
  • 182
  • 2
  • 13

1 Answers1

1

The code should be something like this :

import socket
import threading

ip = "0.0.0.0"
po = 9999

server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind((ip,po))# This line was missing :p thanks
server.listen(5)

print "[*] Listining on %s:%d" %(ip,po)

def handle_client(client_socket):
        request = client_socket.recv(1024)
        print "[*] Received: %s" % request
        client_socket.close()

while True :
        client,addr = server.accept()
        print "[*] Accepted connection from %s:%d" %(addr[0],addr[1])
        client_handler = threading.Thread(target=handle_client,args=(client,))
        client_handler.start()
4bh1
  • 182
  • 2
  • 13