I try to transmit an image from a client to the server,
but it only worked for connection but sending image.
This is the code for the client:
import socket
host = '10.10.40.22'
port = 8888
address = (host, port)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
#connect to the server
s.connect(address)
print('start send image')
with open('doge.png', 'rb') as imgfile:
while True:
imgData = imgfile.readline(1024)
if not imgData:
break
s.send(imgData)
print('end')
and here is the code for the server:
host = '10.10.40.22'
port = 8888
address = (host, port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(1)
print('wait for connection...')
conn, addr = s.accept()
#start to receive picture
with open('Pictures/doge.png', 'wb') as imgfile:
while True:
img_data = conn.recv(1024)
if not img_data:
break
imgfile.write(img_data)
print('writing ...')
conn.close()
s.close()
print('end')
notice that I print a debug message in the code of server that
if it writes any bytes into the image then print the message 'writing'
how can I do now?
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
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 .
When I run the server and the client afterwards, it prints that it got a connection but the data that I sent from the client didn't come through.
Client
import socket
def connect():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 7878
s.connect((host, port))
ter = "terminate"
data = raw_input("-> ")
while ter not in data:
if ter in data:
s.close()
break
else:
rec = s.recv(1024)
print("Recieved:",rec)
data = input("-> ")
connect()
Server
import socket
def connect():
print("Server started")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "127.0.0.1"
port = 7878
s.bind((host, port))
s.listen(1)
c, addr = s.accept()
print("Got connection from", addr)
while True:
data = c.recv(1024)
if len(str(data)) < 0:
c.send("Got nothing send again")
else:
data = data.upper()
c.send(data)
connect()
The example output would end up looking like:
Client Side:
Enter new command: B50
Enter new command H70
Enter new command: Z80
Subscriber side:
Recieved: B50
Recieved: H70
Recieved: Z80
Current Publisher Code
#!/usr/bin/env python
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
def sendMsg(str):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(str.encode())
data = s.recv(BUFFER_SIZE)
s.close()
return
while 1:
MESSAGE = input("Enter Command: ")
sendMsg(MESSAGE)
print ("received data:", data.decode())
Current Subscriber Code
#!/usr/bin/env python
import socket
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print ("received data:", data.decode())
conn.send(data) # echo
conn.close()
Figured out out, had to edit my subscriber code to this
#!/usr/bin/env python
import socket
TCP_IP = ''
TCP_PORT = 5005
BUFFER_SIZE = 20 # Normally 1024, but we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if data:
print ("received data:", data.decode())
conn.send(data) # echo
s.listen(1)
conn, addr = s.accept()
conn.close()