mohamed urrdan
mohamed urrdan

Reputation: 13

A simple socket in python troubles

Am new to the field of network programming, so i thought sockets would be a good place to start. I made a simple one but it keeps throwing back an error.

this is the error

 Traceback (most recent call last):
  File "/Users/mbp/Desktop/python user files/Untitled.py", line 3, in <module>
   client_socket.connect(('localhost', 5000))
 File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
   return getattr(self._sock,name)(*args)
error: [Errno 61] Connection refused

the serve

import socket
import os
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=socket.gethostbyname('localhost')
port=12345
s.bind((host,port))

s.listen(5)
print host
while True:
   c, addr = s.accept()     
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()

the client

import socket
import os     

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
host = '192.168.0.10' 
port = 12345                

s.connect((host, port))
print s.recv(1024)
s.close         

Its only after i run the client that i get the error. Also is it much to run it on the command prompt

Upvotes: 0

Views: 1229

Answers (3)

Donat Pants
Donat Pants

Reputation: 369

Here is an example of a simple command server: if you run the server code and then run the client you will be able to type in the client and send to the server. if you type TIME you will get from the server a respons which contains a string that has the date of today and the other commands work in the same way. if you type EXIT it will close the connection and will send from the server the string closing to the client

server:

import socket
import random
from datetime import date


server_socket = socket.socket()                           # new socket object
server_socket.bind(('0.0.0.0', 8820))                     # empty bind (will connect to a real ip later)

server_socket.listen(1)                                   # see if any client is trying to connect

(client_socket, client_address) = server_socket.accept()  # accept the connection
while True: # main server loop
    client_cmd = client_socket.recv(1024)                 # recive user input from client
    # check waht command was entered
    if client_cmd == "TIME":
        client_socket.send(str(date.today()))             # send the date
    elif client_cmd == "NAME":
        client_socket.send("best server ever")            # send this text
    elif client_cmd == "RAND":
        client_socket.send(str(random.randrange(1,11,1))) # send this randomly generated number
    elif client_cmd == "EXIT":
        client_socket.send("closing")
        client_socket.close()                             # close the connection with the client
        server_socket.close()                             # close the server
        break
    else :
        client_socket.send("there was an error in the commend sent")

client_socket.close()                                     # just in case try to close again
server_socket.close()                                     # just in case try to close again

client:

import socket

client_socket = socket.socket()                    # new socket object
client_socket.connect(('127.0.0.1', 8820))         # connect to the server on port 8820, the ip '127.0.0.1' is special because it will always refer to your own computer

while True:
    try:
        print "please enter a commend"
        print "TIME - request the current time"
        print "NAME - request the name of the server"
        print "RAND - request a random number"
        print "EXIT - request to disconnect the sockets"
        cmd = raw_input("please enter your name") # user input

        client_socket.send(cmd)                   # send the string to the server

        data = client_socket.recv(1024)           # recive server output
        print "the server sent: " + data          # print that data from the server
        print
        if data == "closing":
            break
    except:
        print "closing server"
        break

client_socket.close()                             # close the connection with the server

Upvotes: 0

letmutx
letmutx

Reputation: 1416

The server you're starting doesn't have the address 192.168.0.10, rather it is local host. See the localhost address printed when you run server.py. Update the host variable to that address in client.py which will fix the issue.

Upvotes: 1

Donat Pants
Donat Pants

Reputation: 369

What server are you connecting to? the server needs to have a server_socket.accept() in the code to accept the connecting. from only looking at your client it is hard to tell.

in order to help you i will attach a multy client chat that i wrote in python maybe you can learn some python from it it has threading and multy client socket connection if this is too much for you i have something bit more basic just let me know with a comment

server :

import socket
import select
import thread
import random
from datetime import date

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))

server_socket.listen(5)

open_client_sockets = []
open_client_sockets_with_name = []
message_to_send = []

new_name = "new"

# recives a client socket and finds it in the list of open client sockets and returns its name
def find_name_by_socket(current_socket):
    for client_and_name in open_client_sockets_with_name:
        (client_address, client_name) = client_and_name
        if client_address == current_socket:
            return client_name 

# this function takes a commend, executes it and send the result to the client
def execute(cmd):
    if cmd == "DATE":
        current_socket.send(str(date.today()))
    elif cmd == "NAME":
        current_socket.send("best server ever")
    elif cmd == "RAND":
        current_socket.send(str(random.randrange(1,11,1)))
    elif cmd == "EXIT":
        current_socket.send("closing")
        open_client_sockets.remove(current_socket)
        open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
        current_socket.close()
    else :
        current_socket.send("there was an error in the commend sent")

def send_waiting_message(wlist):
    # sends the message that needs to be sent
    for message in message_to_send:
        (client_socket, name, data) = message

        if data[0] != '`':
            print name + ": " + data
            for client in wlist:
                if client_socket != client:
                    client.send(name + ": " + data)
        else: # this will execute a command and not print it
            print "executing... " + data[1:]
            execute(data[1:])
        message_to_send.remove(message)

while True:
    '''
    rlist, sockets that you can read from
    wlist, sockets that you can send to
    xlist, sockets that send errors '''
    rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets,open_client_sockets , [] )
    for current_socket in rlist:
        if current_socket is server_socket:
            (new_socket, address) = server_socket.accept()
            new_name = new_socket.recv(1024)
            print new_name + " connected"
            open_client_sockets.append(new_socket)
            open_client_sockets_with_name.append((new_socket, new_name))
        else:
            data = current_socket.recv(1024)
            if data == "":
                try:
                    open_client_sockets.remove(current_socket)
                    open_client_sockets_with_name.remove((current_socket, find_name_by_socket(current_socket)))
                except:
                    print "error"
                print "connection with client closed"
            else:

                message_to_send.append((current_socket, str(find_name_by_socket(current_socket)) ,  str(data)))

    send_waiting_message(wlist)

server_socket.close()

client:

import socket
import threading
global msg

# recives input from the server
def recv():
    while True:
        try: # try to recive that data the the server is sending
            data = client_socket.recv(1024)
            print data
        except: # the connection is closed
            return

# send user input to the server
def send():
    while True: # store what the user wrote in the global variable msg and send it to the server
        msg = raw_input("--- ")
        client_socket.send(msg)
        if msg == "`EXIT":
            client_socket.close()
            return

name = raw_input("enter your name ")
print "use ` to enter a commend"

try:
    client_socket = socket.socket()             # new socket
    client_socket.connect(('127.0.0.1', 8820))  # connect to the server
    client_socket.send(name)                    # send the name to the server

    # since receving the server's output and sending the user's input uses blocking functions it is required to run them in a separate thread
    thread_send = threading.Thread(target = send) # creates the thread in charge of sending user input
    thread_recv = threading.Thread(target = recv) # creates the thread in charge of reciving server output

    thread_recv.start() # starts the thread
    thread_send.start() # starts the thread
except:
    print "an error occurred in the main function"
    client_socket.close()

Upvotes: 1

Related Questions