Search code examples
pythonsocketsnetwork-programmingserverclient

How to communicate from one python script with another via network?


I have a server side (Python 3) and a client side (Python 2.7), i am trying to use the socket module. The idea is, that the server side is permanently active and the client socket connects through call of a function. Then data needs to be sent from server to client until the client disconnects (manually). The server should then go back into the listening process and wait until the next connection. I do not have any experience with sockets, i have been trying some examples that i found. In the first line, my problem is to reconnect to the same server socket.

Server side:

import socket

HOST = "127.0.0.1"
PORT = 65432
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))

s.listen()
conn, addr = s.accept()
print("Connected by", addr)

for x in range(10):
    data = conn.recv(1024)
    if not data:
        break
    conn.sendall(data)

conn.close()

Client side (with Tkinter-GUI):

import Tkinter as tk
import socket
import random
import time
keyState = False
HOST = '127.0.0.1'
PORT = 65432


def onButton():
    global keyState 

    if(not keyState ):
        keyState = not keyState 
        key_button.config(relief='sunken')
        connectSocket()
        print(keyState)
        return
    if(keyState ):
        keyState = not keyState 
        key_button.config(relief='raised')
        disconnectSocket()
        print(keyState )
        return


def connectSocket():
    print("connectSocket()")
    global HOST, PORT
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((HOST, PORT))
    for x in range(10):
        if(x<5):
            val = random.uniform(0.0, 400.0)
        else:
            val = random.uniform(-400,0)
        s.sendall(str(val))
        data = s.recv(1024)
        print 'Received', repr(data)
    s.close()

    
def disconnectSocket():
    print("disconnectSocket()")
    return


#Main GUI
root = tk.Tk()
root.title('Python Socket Test')
root.configure(background='white')
root.geometry("200x300")


#Button
root.update()
softkey_button = tk.Button(root, text="Softkey", command = lambda: onButton(), relief='flat')
softkey_button.place(x=75,y=200)


root.mainloop()

Solution

  • You simply need to add a while True loop on your server side, corrently you are only accepting one connection, and after the connection is closed the program stops. Try this on your server file:

    import socket
    
    HOST = "127.0.0.1"
    PORT = 65432
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((HOST, PORT))
    
    while True:
        s.listen()
        conn, addr = s.accept()
        print("Connected by", addr)
        
        for x in range(10):
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)
        
        conn.close()