Python Forum
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
check my tcp code plz
#1
hi I'm running python on ma terminal using the command "python _____.py" and it runs the code. i made a simple tcp server, but with all the help that people gave me , i don't know how to connect to it from another pc. i can connect with as many windows of terminal on my pc, but not any other pc.


server is called "chat_server.py"
 



  GNU nano 2.0.6            File: chat_server.py                                

              # Tcp Chat server

 

import socket, select

 

#Function to broadcast chat messages to all connected clients

def broadcast_data (sock, message):

    #Do not send the message to master socket and the client who has send us the message

    for socket in CONNECTION_LIST:

        if socket != server_socket and socket != sock :

            try :

                socket.send(message)

            except :

                # broken socket connection may be, chat client pressed ctrl+c for example

                socket.close()

                CONNECTION_LIST.remove(socket)

 

if __name__ == "__main__":

     

    # List to keep track of socket descriptors

    CONNECTION_LIST = []

    RECV_BUFFER = 4096 # Advisable to keep it as an exponent of 2

    PORT = 5432

     

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

    # this has no effect, why ?

    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_socket.bind(("0.0.0.0", PORT))

    server_socket.listen(10)

 

    # Add server socket to the list of readable connections

    CONNECTION_LIST.append(server_socket)

 

    print "Chat server started on port " + str(PORT)

 

    while 1:

        # Get the list sockets which are ready to be read through select

        read_sockets,write_sockets,error_sockets = select.select(CONNECTION_LIST,[],[])

 

        for sock in read_sockets:

            #New connection

            if sock == server_socket:

                # Handle the case in which there is a new connection recieved through server_socket

                sockfd, addr = server_socket.accept()

                CONNECTION_LIST.append(sockfd)

                print "Client (%s, %s) connected" % addr

                 

                broadcast_data(sockfd, "[%s:%s] entered room\n" % addr)

             

            #Some incoming message from a client

            else:

                # Data recieved from client, process it

                try:

                    #In Windows, sometimes when a TCP program closes abruptly,

                    # a "Connection reset by peer" exception will be thrown

                    data = sock.recv(RECV_BUFFER)

                    if data:

                        broadcast_data(sock, "\r" + '<' + str(sock.getpeername()) + '> ' + data)                

                 

                except:

                    broadcast_data(sock, "Client (%s, %s) is offline" % addr)

                    print "Client (%s, %s) is offline" % addr

                    sock.close()

                    CONNECTION_LIST.remove(sock)

                    continue

     
    server_socket.close()

    
tcp chat server called "client.py"
# telnet program example
import socket, select, string, sys
 
def prompt() :
    sys.stdout.write('<You> ')
    sys.stdout.flush()
 
#main function
if __name__ == "__main__":
     
    if(len(sys.argv) < 3) :
        print 'Usage : python telnet.py hostname port'
        sys.exit()
     
    host = sys.argv[1]
    port = int(sys.argv[2])
     
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
     
    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print 'Unable to connect'
        sys.exit()
     
    print 'Connected to remote host. Start sending messages'
    prompt()
     
    while 1:
        socket_list = [sys.stdin, s]
         
        # Get the list sockets which are readable
        read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
         
        for sock in read_sockets:
            #incoming message from remote server
            if sock == s:
                data = sock.recv(4096)
                if not data :
                    print '\nDisconnected from chat server'
                    sys.exit()
                else :
                    #print data
                    sys.stdout.write(data)
                    prompt()
             
            #user entered a message
            else :
                msg = sys.stdin.readline()
                s.send(msg)
                prompt()
if u can change whatever is needed to make this  a tcp server that i can use the client from multiple computers and connect to the server. that would be very appreciated.

idk why it did size x= small... just the forum did that thats not part of the code.
Reply
#2
(Mar-30-2017, 07:45 PM)abrew132 Wrote: idk why it did size x= small... just the forum did that thats not part of the code.

I fixed that for you. It happens when copy-pasting from some text editors. In order to avoid it in the future, you can right click and "paste without formatting", or I think maybe shift+ctrl+v. Or, you can do what I did, and just highlight all the text in your post, and click the A with the red minus sign (hover-text is "remove formatting"), which removes all formatting from the post.

This might be an operating system issue. Most of the time, you have to specifically open a port so other computers can access it, otherwise it only works on the local machine.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Code to check folder and sub folders for new file and alert fioranosnake 2 1,933 Jan-06-2022, 05:03 PM
Last Post: deanhystad
  Try,Except,Else to check that user has entered either y or n (Code block pasted) RandomNameGenerator 3 2,329 Jun-29-2021, 08:21 PM
Last Post: RandomNameGenerator
  Can somebody check what is wrong with my code? hplus_liberation 4 2,594 Sep-16-2020, 05:52 AM
Last Post: perfringo
  Condition check differences and how to organise code? adam2020 4 2,668 May-12-2019, 04:12 PM
Last Post: Yoriz
  Python code to check SQL table for current date PYTHONDUDE 3 2,945 May-16-2018, 02:27 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020