two different remote server communication using python - python

this is a server code that i am running on remote server.
serv.py
import time, socket, sys
print('Setup Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host_name = socket.gethostname()
ip = socket.gethostbyname(host_name)
port = 1234
soc.bind((host_name, port))
print(host_name, '({})'.format(ip))
name = input('Enter name: ')
soc.listen(1) #Try to locate using socket
print('Waiting for incoming connections...')
connection, addr = soc.accept()
print("Received connection from ", addr[0], "(", addr[1], ")\n")
print('Connection Established. Connected From: {}, ({})'.format(addr[0], addr[0]))
#get a connection from client side
client_name = connection.recv(1024)
client_name = client_name.decode()
print(client_name + ' has connected.')
print('Press [bye] to leave the chat room')
connection.send(name.encode())
while True:
message = input('Me > ')
if message == 'bye':
message = 'Good Night...'
connection.send(message.encode())
print("\n")
break
connection.send(message.encode())
message = connection.recv(1024)
message = message.decode()
print(client_name, '>', message)
This is client code that i am running on local system.
clie.py
import time, socket, sys
print('Client Server...')
time.sleep(1)
#Get the hostname, IP Address from socket and set Port
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
#get information to connect with the server
print(shost, '({})'.format(ip))
server_host = input('Enter server\'s IP address:')
name = input('Enter Client\'s name: ')
port = 1234
print('Trying to connect to the server: {}, ({})'.format(server_host, port))
time.sleep(1)
soc.connect((server_host, port))
print("Connected...\n")
soc.send(name.encode())
server_name = soc.recv(1024)
server_name = server_name.decode()
print('{} has joined...'.format(server_name))
print('Enter [bye] to exit.')
while True:
message = soc.recv(1024)
message = message.decode()
print(server_name, ">", message)
message = input(str("Me > "))
if message == "bye":
message = "Leaving the Chat room"
soc.send(message.encode())
print("\n")
break
soc.send(message.encode())
Now if the host server is different the connection is not established. but if the host is same then it's working properly and sending texts properly. i want run this code in different server how to do please help me anyone.

In the server script, you use :
host_name = socket.gethostname()
This will probably give you "127.0.0.1".
What you need is for the server to listen to "0.0.0.0" to accept connections from everywhere.
So this will probably do :
host_name = "0.0.0.0"

Related

Python socket library: OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected

OSError: [WinError 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied.
I am getting the above error..My server and client can send and receive their first messages but I get this error if I try to send more than one message.
My Server Code is here
import socket
import threading
import time
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5354
maxconnections = 9
ip = socket.gethostbyname(socket.gethostname())
print(ip)
server = (ip, port)
FORMAT = 'utf-8'
listensocket.bind((server))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
msg = f'\[ALERT\] {address} has joined the chat.'
lstbox.insert(0, msg)
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Client: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5986
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
And my client code is same with minor difference
import socket
import time
import threading
from tkinter import *
#functions
def t_recv():
r = threading.Thread(target=recv)
r.start()
def recv():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listensocket:
port = 5986
maxconnections = 9
ip = socket.gethostname()
print(ip)
FORMAT = 'utf-8'
host = 'MY_IP' # My actual ip is there in the code
listensocket.bind((host, port))
listensocket.listen(maxconnections)
(clientsocket, address) = listensocket.accept()
while True:
sendermessage = clientsocket.recv(1024).decode(FORMAT)
if not sendermessage == "":
time.sleep(3)
lstbox.insert(0, 'Server: ' +sendermessage)
def t_sendmsg():
s = threading.Thread(target=sendmsg)
s.start()
at = 0
def sendmsg():
global at
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
hostname = 'Lenovo-PC'
port = 5354
if at==0:
g.connect((hostname, port))
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
at += 1
else:
msg = messagebox.get()
lstbox.insert(0, 'You: ' +msg)
g.send(msg.encode())
Please let me know what changes are required to be made in order to make it run for every message.
I tried to put
g.connect((hostname, port))
the above line in the loop so that it will connect every time loop iterates. But it did not help.
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as g:
...
if at==0:
g.connect((hostname, port))
...
g.send(msg.encode())
at += 1
else:
...
g.send(msg.encode())
In the if at==0 condition it connects to the server, in the else part not. But is still trying to send something on the not connected socket.

Python Chatroom: Sending messages while receving messages

I have created two chatroom programs. The idea is that the server and client(s) can transfer messages between each other.
The current situation is that the server cannot receive messages whilst entering messages neither can client type messages whilst waiting for server to send.
I have been looking at threading to solve this problem but haven't got a clue to implement it.
Server code:
#Chatroom Server
import socket
import threading
host = socket.gethostname()
ip = socket.gethostbyname(host)
print('Host name:', host)
print('Host IP:' , ip)
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((ip,port))
name = input('Enter host name:')
s.listen(3)#Allows maximum 3 connections to server
conn,addr = s.accept()
print('Connection established with: ', addr[0])
client = (conn.recv(1024)).decode()
print(client + ' connected')
conn.send(name.encode())
while True:
msg = input('You:')
choice = False
while True:
choice = input('Do you want to enter another line? (Y/N)')
if choice.upper() == 'Y':
add_msg= input("You:")
msg = msg + '\n' +add_msg
else:
break
conn.send(msg.encode())
msg = conn.recv(1024)
msg = msg.decode()
print(client+':'+msg)
Client code:
#Chatroom Client
import socket
hip = 'xxx.xx.xx.xx' #hip = host ip
port = 8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((hip,port))
name = input('Enter username:')
s.send(name.encode())
hname = s.recv(1024)
hname = hname.decode()
while True:
smsg = (s.recv(1024).decode())
print(hname+':'+smsg)
msg = input('You:')
choice = False
while True:
choice = input('Do you want to enter another line? (Y/N)')
if choice.upper() == 'Y':
add_msg= input("You:")
msg = msg + '\n' +add_msg
else:
break
s.send(msg.encode())

Echo server chat application having issues connecting

I'm a novice when it comes to networking, but for my distributed systems project I'm attempting to create a simple application that allows any computer on the same network with python to send messages to a server. I cannot get my computer and laptop to connect successfully, and I get a timeout error on the client side:
Here is my server code:
import socket
import select
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 1234
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()
sockets_list = [server_socket]
clients = {}
def receive_message(client_socket):
try:
message_header = client_socket.recv(HEADER_LENGTH)
if not len(message_header):
return False
message_length = int(message_header.decode("utf-8").strip())
return {"header": message_header, "data" : client_socket.recv(message_length)}
except:
return False
while True:
read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)
for notified_socket in read_sockets:
if notified_socket == server_socket:
client_socket, client_address = server_socket.accept()
user = receive_message(client_socket)
if user is False:
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print(f"Accepted new connection from {client_address[0]}:{client_address[1]} username:{user['data'].decode('utf-8')}")
else:
message = receive_message(notified_socket)
if message is False:
print(f"Closed connection from {clients[notified_socket]['data'].decode('utf-8')}")
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue
user = clients[notified_socket]
print(f"Received message from {user['data'].decode('utf-8')}: {message['data'].decode('utf-8')}")
for client_socket in clients:
if client_socket != notified_socket:
client_socket.send(user['header'] + user['data'] + message['header'] + message['data'])
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
Here is my client code
import socket
import select
import errno
import sys
HEADER_LENGTH = 10
IP = "127.0.0.1"
PORT = 1234
my_username = input("Username: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblocking(False)
username = my_username.encode("utf-8")
username_header = f"{len(username):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(username_header + username)
while True:
message = input(f"{my_username} > ")
if message:
message = message.encode("utf-8")
message_header = f"{len(message):<{HEADER_LENGTH}}".encode("utf-8")
client_socket.send(message_header + message)
try:
while True:
#receive things
username_header = client_socket.recv(HEADER_LENGTH)
if not len(username_header):
print("connection closed by the server")
sys.exit()
username_length = int(username_header.decode("utf-8").strip())
username = client_socket.recv(username_length).decode("utf-8")
message_header = client_socket.recv(HEADER_LENGTH)
message_length = int(message_header.decode("utf-8").strip())
message = client_socket.recv(message_length).decode("utf-8")
print(f"{username} > {message}")
except IOError as e:
if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
print('Reading error', str(e))
sys.exit()
continue
except Exception as e:
print('General error', str(e))
sys.exit()
On the same machine, it works as expected since I'm using the hostname for both the server and client, but obviously, it will not work on separate devices.
How may I change this code so that I can get my laptop to act as a client, and my computer to act as a server? I only need to connect to devices on the same network. Thank you for any answers.
I found the solution myself, I just had to set the 'IP' in client to that of the server local IP, and lastly run both in IDLE so I would get the prompt to bypass the firewall, as I was running cmd previously and was not getting the option to bypass.

Python socket chat server only listens to one client

Hi I am working on a self made chat server using python and sockets. I was trying to finish the entire thing without a tutorial but I have been stuck on this for about 4 days now and decided to get some help.
I have gotten far enough that the server can have clients connect to it, it can store there data, and receive and send out messages, My problem is that after connecting two clients and sending about 4 messages the server stops receiving messages from one of the two clients. But the client that can no longer send messages can still see incoming messages from the other client
Here is the code for my server
import socket
import threading
HEADER = 100
PORT = 1234
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
#list of all connected clients
cl = []
#is run when i new client connects
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg = conn.recv(2048).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
for i in range(threading.activeCount() - 1):
print(" ")
conn = cl[i]
print(" ")
conn.send(msg.encode(FORMAT))
conn.close()
#scans for new clients
def start():
server.listen(5)
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
client_con = threading.Thread(target=handle_client, args=(conn, addr))
client_con.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print(" ")
#adds new client to clients list
cl.append(conn)
print("[STARTING] server is starting...")
start()
And here is the code for my client
import socket
import threading
HEADER = 100
PORT = 1234
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER,PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
#get users name that is show befor message's
def get_info():
name = input("whats your name: ")
NAME = name
NAME = NAME + "-"
return NAME
#sends messags's to server
def send_msg():
NAME = get_info()
while True:
print(" ")
msg = input("type your message: ")
print(" ")
msg = NAME + " " + msg
message = msg.encode(FORMAT)
client.send(message)
#recives messages from server
def recs():
while True:
print(" ")
msg_rcv = client.recv(5000)
print(msg_rcv.decode(FORMAT))
print(" ")
send = threading.Thread(target=send_msg)
rec = threading.Thread(target=recs)
rec.start()
send.start()
Thank you for reading and any help is very apricated have a great day! <:
Well turns out i finally found my issues after making a flow chart to help me visualize where an issue could occur.
the issue was in my server and had to do with the con variable in this strip of code
msg = conn.recv(2048).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
connected = False
for i in range(threading.activeCount() - 1):
print(" ")
conn = cl[i]
print(" ")
conns.sendall(msg.encode(FORMAT))
i just needed to use a diffrent var for sending the message so here is the working server code
import socket
import threading
HEADER = 100
PORT = 1234
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "DISCONNECT"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
#list of all connected clients
cl = []
#is run when i new client connects
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg = conn.recv(2048).decode(FORMAT)
print(f"[MSG IS]--> {msg}")
if msg == DISCONNECT_MESSAGE:
connected = False
for i in range(threading.activeCount() - 1):
print(" ")
conns = cl[i]
print(" ")
conns.sendall(msg.encode(FORMAT))
#conn.close()
#scans for new clients
def start():
server.listen(5)
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
client_con = threading.Thread(target=handle_client, args=(conn, addr))
client_con.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print(" ")
#adds new client to clients list
cl.append(conn)
print("[STARTING] server is starting...")
start()
#we need to find a way to send a message from a client to all other clients!
all i had to do was change one of the conn to conns so it would not mix things up!

Python socket ssl connetion

Here is the senario:
Server listens to two ports 9999, 9998 via the host 10.10.10.1
Port 9999 for clients & Port 9998 for the controller
I was able to connect client and the controller to the server and control the client from the controller without ssl socket.
I wanted to use encrypted socket I added ssl certificate socket connection, The client does not connect to the server via SSL_SOCK as the controller too.
I appreciate your help or suggetion.
server :
s=socket(AF_INET, SOCK_STREAM)
s.bind(("10.10.10.1",9999))
s.listen(5)
port = 9999
password = "password"
bridgeport = 9998
allConnections = []
allAddresses = []
def getConnections():
for item in allConnections:
item.close()
del allConnections[:]
del allAddresses[:]
while 1:
try:
q,addr=s.accept()
connstream = ssl.wrap_socket(q, server_side=True, certfile="server.crt", keyfile="server.key", ssl_version=ssl.PROTOCOL_SSLv23)
connstream.setblocking(1)
allConnections.append(connstream)
allAddresses.append(addr)
except:
print "YOU ARE NOT CONNECTED!! TRY AGAIN LATER"
time.sleep(10.0)
break
def main():
bridge=socket(AF_INET, SOCK_STREAM)
bridge.bind(("10.10.10.1",9998))
bridge.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
while 1:
bridge.listen(1)
q,addr=bridge.accept()
bridgestream = ssl.wrap_socket(q, server_side=True, certfile="server.crt", keyfile="server.key", ssl_version=ssl.PROTOCOL_SSLv23)
cpass = bridgestream.recv(4096)
if (cpass == password):
print "Controller is connected"
else:
print "Controller not conected"
try:
main()
except:
try:
del allConnections[:]
del allAddresses[:]
except:
pass
Controller :
host = '10.10.10.1'
port = 9998
password = "password"
def main():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = ssl.wrap_socket(s, ca_certs="server.crt", cert_reqs=ssl.CERT_REQUIRED)
ssl_sock.connect((host, port))
except:
sys.exit("[ERROR] Can't connect to server")
ssl_sock.sendall(password)
Client:
host = "10.10.10.1"
port = 9999
def main(host, port):
while 1:
connected = False
while 1:
while (connected == False):
try:
print host
print port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print s
ssl_sock = ssl.wrap_socket(s, ca_certs="server.crt", cert_reqs=ssl.CERT_REQUIRED)
print "ssl_sock"
ssl_sock.connect((host,port))
print "Connected"
connected = True
except:
print "The client not Connected yet"
time.sleep(5)
while 1:
try:
main(host, port)
except:
time.sleep(5)
I had a similar issue and would suggest two approaches:
Try raw TCP socket first (without ssl.wrap_socket()). If this works, use a tool such as netstat to diagnose what ports and IP addresses are used, in case something is blocking either.
Try creating an SSLContext on either side with something like this:
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
ssl_context.verify_mode = ssl.CERT_NONE
stream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
_socket = ssl_context.wrap_socket(stream_socket, server_hostname=hostname)
_socket.connect((hostname, port))
In other words, don't enforce certificate usage first and try specifying protocol. Hope this helps!

Categories