-2

I am trying to create a TCP server on my local host, but when I run my program, it doesn't do anything.

Does anyone know why?

import socket

def creat_listen_sock():
    PORT = 9090
    listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('', PORT)
    listening_sock.bind(server_address)
    listening_sock.listen(1)
    client_sock, client_address = listening_sock.accept()
    listening_sock.close()
    mas = "hello world"
    client_sock.sendall(mas.encode())
def connect_server():
    SERVER_IP = "127.0.0.1"
    SERVER_PORT = 9090
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (SERVER_IP, SERVER_PORT)
    sock.connect(server_address)
    mas = sock.recv(1024)
    mas = mas.decode()
    print(mas)
    sock.close()
def main():
    creat_listen_sock()
    connect_server()
Josi Whitlock
  • 185
  • 4
  • 15

2 Answers2

2

First of all, you should call main(), because in python main() is not a default entry point as you, probably, expected. Secondly, creat_listen_sock() is blocking. So, connect_server() wouldn't be called. Normally, you should create 2 different processes (i.e. server and client). If you are interested in sharing data inside the same system, you may want to consider using threads, not socket communication.

This would be a working solution:

client.py

import socket

def connect_server():
    SERVER_IP = "127.0.0.1"
    SERVER_PORT = 9090
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (SERVER_IP, SERVER_PORT)
    sock.connect(server_address)
    mas = sock.recv(1024)
    mas = mas.decode()
    print(mas)
    sock.close()

def main():
    connect_server()

main()

server.py

import socket

def creat_listen_sock():
    PORT = 9090
    listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('', PORT)
    listening_sock.bind(server_address)
    listening_sock.listen(1)
    client_sock, client_address = listening_sock.accept()
    listening_sock.close()
    mas = "hello world"
    client_sock.sendall(mas.encode())

def main():
    creat_listen_sock()

main()
Cristian
  • 171
  • 5
0

Try this You need to call the main method.

import socket

def creat_listen_sock():
    PORT = 9090
    listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = ('', PORT)
    listening_sock.bind(server_address)
    listening_sock.listen(1)
    client_sock, client_address = listening_sock.accept()
    listening_sock.close()
    mas = "hello world"
    client_sock.sendall(mas.encode())
def connect_server():
    SERVER_IP = "127.0.0.1"
    SERVER_PORT = 9090
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (SERVER_IP, SERVER_PORT)
    sock.connect(server_address)
    mas = sock.recv(1024)
    mas = mas.decode()
    print(mas)
    sock.close()



if __name__ == "__main__":
    creat_listen_sock()
    connect_server()
user13966865
  • 448
  • 4
  • 13