I am trying to create a simple server and client program. The client will request time sync from the server and server will answer with the current Epoch Time.
I am trying to implement the server as multithread.
When I did for single-thread it worked fine, but now I don't think is working because I keep getting the following message:
line 21, in run
connectionSocket.send(ts.encode())
BrokenPipeError: [Errno 32] Broken pipe
Here is my code
Client1:
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort)) #handshaking between client and server
sentence = 'Hey Server, what is the current time?'
print(sentence)
clientSocket.send(sentence.encode())
currentTime = clientSocket.recv(1024)
print('From Server: ', currentTime.decode())
clientSocket.close()
Multithread server
from threading import Thread
from socketserver import ThreadingMixIn
import calendar
import time
from socket import *
class ClientThread(Thread):
def __init__(self,ip,port):
Thread.__init__(self)
self.ip = ip
self.port = port
print ("New server socket thread started for " + ip + " : " + str(port))
def run(self):
while True :
connectionSocket.recv(2048)
ts = calendar.timegm(time.gmtime())
ts = str(ts)
connectionSocket.send(ts.encode())
#connectionSocket.close() #should I close????
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
#serverSocket.listen(1)
threads = []
#print('The server is ready to receive')
while True:
serverSocket.listen(1) #should this be inside or outside the loop????
print('The server is ready to receive') #and this?????
(connectionSocket, (ip,port)) = serverSocket.accept()
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
for t in threads:
t.join()
My best guess is you are missing the return statement in the server script. It needs a few more fixes, but this should work - run this code:
Client
from socket import *
serverName = '127.0.0.1'
serverPort = 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
try:
clientSocket.connect((serverName, serverPort))
sentence = 'Hey Server, what is the current time?'
print('Data to send:\n\t', sentence)
clientSocket.send(sentence.encode())
currentTime = clientSocket.recv(1024)
print('Received data:\n\t', currentTime.decode())
except Exception as exc:
print(exc)
finally:
clientSocket.close()
Server
from threading import Thread
import calendar
import time
from socket import *
class ClientThread(Thread):
def __init__(self, ip, port):
Thread.__init__(self)
self.ip = ip
self.port = port
print("New server socket thread started for " + ip + ":" + str(port))
def run(self):
while True :
print('Receiving data from a client')
data = connectionSocket.recv(2048) # if data is coming to the server, code will go further than this line
print('Received data:\n\t', data)
ts = calendar.timegm(time.gmtime())
ts = str(ts)
print('Sending a data:\n\t', ts)
connectionSocket.send(ts.encode())
return
serverPort = 12000
threads = []
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1) # can accept and be connected to one connection at a time
while True:
print('The server is ready to receive')
(connectionSocket, (ip, port)) = serverSocket.accept()
newthread = ClientThread(ip, port)
newthread.start()
threads.append(newthread)
# for t in threads:
# t.join()
Related
I'm trying to repurpose this script, I want the server to send messages to my client, and I want the client to be the one that 'reaches out' and makes the connection. As you can see, with the script I have, the client is the one reaching out but it's the one that can send the messages to the server. I've tried looking at other scripts, moving the send and handle function around, but I feel like my inexperience with sockets got me stumped. Any help would be appreicated.
Server:
import socket
import threading
HEADER = 64
PORT = 5430
SERVER = '192.110.100.189' # socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!END'
# defines the type of connection
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
def handle_client(conn, addr):
print(f'[NEW CONNECTIONS] {addr} connected')
connected = True
while connected:
# the header variable here acts as a protocol to give us an idea of how many bytes are being sent
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg == DISCONNECT_MESSAGE:
break
print(f'{addr} | {msg}')
conn.send('msg recieved'.encode(FORMAT))
conn.close()
def start():
server.listen()
print(f'[LISTENING] Server is listening on {SERVER}')
while True:
conn, addr = server.accept()
thread = threading.Thread(target = handle_client, args = (conn, addr))
thread.start()
print(f'[ACTIVE CONNECTIONS] {threading.activeCount() - 1}')
print('[STARTNG] Server is starting')
start()
Client:
import socket
HEADER = 64
PORT = 5430
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = '!END'
SERVER = '192.110.100.189'
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
while True:
enter = input('CLIENT - ')
send(enter)
if enter == DISCONNECT_MESSAGE:
break
Hi I was following a tech with Tim tutorial about sockets and I am building a chat app and I am trying to create a dictionary with the names and the IP in it. but when I connect and type my name the client-side app freezes but I don't know why so can you see if you can help me this is the code.
Server-side code
import socket
import threading
import io
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
Names = {}
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg.split(':::')[0] == 'Name':
name = msg.split(':::')[-1]
Names[addr] = name
print(Names.get(addr))
elif msg == DISCONNECT_MESSAGE:
connected = False
print(f'[{addr}] Has disconnected')
# Names.pop(addr)
else:
conn.send('message recieved'.encode(FORMAT))
print(msg)
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
And this is the client-side code
import socket
HEADER = 64
PORT = 5050
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
SERVER = '127.0.1.1'
print(SERVER)
Name = input('Enter your name: ')
ADDR = (SERVER, PORT)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)
def send(msg):
message = msg.encode(FORMAT)
msg_length = len(message)
send_length = str(msg_length).encode(FORMAT)
send_length += b' ' * (HEADER - len(send_length))
client.send(send_length)
client.send(message)
print(client.recv(2048).decode(FORMAT))
send('Name:::' + Name)
while True:
msg = input('what message do you want to send type dis to disconnect: ')
if msg != DISCONNECT_MESSAGE :
send(msg)
elif msg == DISCONNECT_MESSAGE:
send(msg)
break
elif msg == None:
print("please type a message and don't leave it a blank")
In your client code, under function send(msg) you are expecting response from server once the client sent a message, and you are using the same function for sending username as well.
In the server you have not coded to respond for username.
Hence your client is actually waiting for response from server, for the username it just sent. That's why it looks frozen.
Adding a response like Hello username in server will resolve this.
Server
import socket
import threading
import io
HEADER = 64
PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "dis"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
Names = {}
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected.")
connected = True
while connected:
msg_length = conn.recv(HEADER).decode(FORMAT)
if msg_length:
msg_length = int(msg_length)
msg = conn.recv(msg_length).decode(FORMAT)
if msg.split(':::')[0] == 'Name':
name = msg.split(':::')[-1]
Names[addr] = name
print(Names.get(addr))
conn.send(f'Hello {name}'.encode(FORMAT))
elif msg == DISCONNECT_MESSAGE:
connected = False
print(f'[{addr}] Has disconnected')
# Names.pop(addr)
else:
conn.send('message recieved'.encode(FORMAT))
print(msg)
conn.close()
def start():
server.listen()
print(f"[LISTENING] Server is listening on {SERVER}")
while True:
conn, addr = server.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")
print("[STARTING] server is starting...")
start()
I have server and client codes, and I want someone out of my local network to send and recieve messages from my server, but he gets an error:
"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it"
Server code:
import socket
LISTEN_PORT = 4444
def server():
listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('', LISTEN_PORT)
listening_sock.bind(server_address)
listening_sock.listen(1)
client_soc, client_address = listening_sock.accept()
client_msg = client_soc.recv(1024).decode()
print(client_msg)
msg = 'server msg'
print("sent")
client_soc.sendall(msg.encode())
def main():
server()
if __name__ == "__main__":
main()
Cient code:
import socket
SERVER_IP = "<my local ip address>"
SERVER_PORT = 4444
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (SERVER_IP, SERVER_PORT)
sock.connect(server_address)
msg = input("Enter msg: ")
sock.sendall(msg.encode())
print(sock.recv(1024).decode())
def main():
client()
if __name__ == "__main__":
main()
I've tried searching in stack overflow already but I couldn't find anything relevant
Hello I am pretty much new to socket and I was trying to make a connection inside my local computer using socket.
this is the server
import socket
def server():
host = socket.gethostname() # get local machine name
port = 8080 # Make sure it's within the > 1024 $$ <65535 range
s = socket.socket()
s.bind(('192.168.56.1', port))
s.listen(1)
client_socket, adress = s.accept()
print("Connection from: " + str(adress))
while True:
data = s.recv(1024).decode('utf-8')
if not data:
breakpoint
print('From online user: ' + data)
data = data.upper()
s.send(data.encode('utf-8'))
s.close()
if __name__ == '__main__':
server()
and this is the client
import socket
def client():
host = socket.gethostname() # get local machine name
port = 8080 # Make sure it's within the > 1024 $$ <65535 range
s = socket.socket()
s.connect(("192.168.56.1", port))
message = input('-> ')
while message != 'q':
s.send(message.encode('utf-8'))
data = s.recv(1024).decode('utf-8')
print('Received from server: ' + data)
message = input('==> ')
s.close()
if __name__ == '__main__':
client()
I know there are useless lines in there but I will clean it up after I finish my connection .
i cant understand why each time python chooses different port for me even i have specified a static port ,for example last output was :
Server waiting for connection...
Client connected from: ('127.0.0.1', 52480)
here is the code for both client and server side ,just don't know how python does that and also if there a way to impose on python to use port i have set
server
import socket
import threading
def sendMsg(conn):
while True:
msg = input()
conn.send(msg.encode('utf-8'))
def recvMsg(conn):
while True:
msg = conn.recv(1024)
print(msg.decode('utf-8'))
if __name__ == '__main__':
server_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8000))
server_socket.listen(5)
print('Server waiting for connection...')
client_sock, addr = server_socket.accept()
print('Client connected from: ', addr)
obj1 = threading.Thread(None, target=sendMsg, args=(client_sock,))
obj2 = threading.Thread(None, target=recvMsg, args=(client_sock,))
obj1.start()
obj2.start()
obj1.join()
obj2.join()
client_sock.close()
server_socket.close()
client side
import socket
import threading
def sendMsg(conn):
while True:
msg = input()
conn.send(msg.encode('utf-8'))
def recvMsg(conn):
while True:
msg = conn.recv(1024)
print(msg.decode('utf-8'))
if __name__ == '__main__':
client_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock_addr= ('127.0.0.1',8000)
client_sock.connect(sock_addr)
obj1 = threading.Thread(None, target=sendMsg, args=(client_sock,))
obj2 = threading.Thread(None, target=recvMsg, args=(client_sock,))
obj1.start()
obj2.start()
obj1.join()
obj2.join()
print('Socket is closed!!!')
client_sock.close()