Итак, я создал очень простую клиентскую и серверную программу на Python, которая прекрасно работает как на моем локальном компьютере.
Но скажите, был ли Клиент на другом компьютере и сервер на другом. Как мне изменить или что реализовать в своем коде, чтобы соединить сервер и клиент вместе, не находясь на одной машине?
smallserver.py
import socket as mysoc
import threading
import time
import random
# ts server task
def server():
# creating ts server socket
global ts
try:
ts=mysoc.socket(mysoc.AF_INET, mysoc.SOCK_STREAM)
print("ts Server socket created")
except mysoc.error as err:
print('{} \n'.format("socket open error ",err))
# bind and listen to client
server_binding=('',50006)
ts.bind(server_binding)
ts.listen(1)
# accept client socket connection request
csockid,addr = ts.accept()
print ("[ts Server]: Got a connection request from a client at", addr)
# send a intro message to the client.
msg = "Connected to ts.py server"
csockid.send(msg.encode('utf-8'))
# receiving and decoding message sent from client
data_from_client = (csockid.recv(1024))
word = data_from_client.decode('utf-8').lower()
print('[Client]: ' + word)
# close the ts server socket
ts.close()
exit()
# threading
t1 = threading.Thread(name='server', target = server)
t1.start()
time.sleep(random.random()*5)
exit()
# END OF TS SERVER PROGRAM
smallclient.py
import threading
import socket as mysoc
# client
def client():
# creating 2 different sockets
global cs
try:
cs = mysoc.socket(mysoc.AF_INET, mysoc.SOCK_STREAM)
print("[Client]: 1st client socket created")
except mysoc.error as err:
print('{} \n'.format("socket open error ", err))
# defining ports of both potential servers
rsListenport = 50006
sa_sameas_myaddr = mysoc.gethostbyname(mysoc.gethostname())
# connect to the rs server on local machine
print("[Client] = Connecting to rs server.....")
server_binding = (sa_sameas_myaddr, rsListenport)
cs.connect(server_binding)
# printing acknowledgement message from rs server
data_from_server = cs.recv(100)
print("[rs Server]: ", data_from_server.decode('utf-8'))
# closing both client sockets
cs.close()
exit()
# threading
t2 = threading.Thread(name='client', target=client)
t2.start()
exit()
# END OF CLIENT PROGRAM