python 3 tcp server and client string transfer error - python-3.x

I try to develop a simple server and client program, I run the code with python 3.4.2.( on Debian 8.6 ) . The server run well, the client program connect's to the server but when I pass a text in terminal to send to server and send back with time stamp, I get this error in the client terminal window
Traceback (most recent call last):
File "tcp_client", line 15, in
tcpCliSock.send(data)
TypeError: 'str' does not support the buffer interface
this is the server code
from socket import *
from time import ctime
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
while True:
print('waiting for connection...')
tcpCliSock, addr = tcpSerSock.accept()
print('....connected from :', addr)
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (bytes(ctime(), 'utf-8'), data))
tcpCliSock.close()
tcpSerSock.close()
and this it the client code
from socket import *
HOST = '192.168.0.141'
PORT = 21577
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
data = input('> ')
if not data:
break
tcpCliSock.send(data)
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
print(data.decode('utf-8'))
tcpCliSock.close()

Related

Server to Client Multithread Python

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()

Trouble getting my server to respond back to client | Python | Sockets

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

Get an empty png image using socket in Python

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?

Connection error between server client OS error

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 .

python3: two clients sending data to server using sockets

I'm working with 3 raspberry pi, one as a server and the two others are clients. What I want to do is to make the clients communicate with the server simultaneously, I don't want to wait for client1 communication to be done in order to launch client2 request to the server (which I succeeded to do). However, I want each client to send different data to server at the same time. I tried to use Sockets and threading, like below.
server code:
import socket
import RPi.GPIO as GPIO
from threading import Thread
# Multithreaded Python server : TCP Server Socket Thread Pool
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 :
data = conn.recv(2048)
data = data.decode('utf-8')
print ("Server received data:", data)
MESSAGE = input("Multithreaded Python server : Enter Response from Server/Enter exit:")
if MESSAGE == 'exit':
break
conn.send(str.encode(MESSAGE)) # echo
# Multithreaded Python server : TCP Server Socket Program Stub
TCP_IP = ''
TCP_PORT = 9050
BUFFER_SIZE = 2000 # Usually 1024, but we need quick response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(2)
threads = []
list_data=[]
while True:
print ("Multithreaded Python server : Waiting for connections from TCP clients...")
(conn, (ip,port)) = s.accept()
data = conn.recv(2048)
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
list_data.append(data)
for t in threads:
t.join()
client1 code:
import socket
import RPi.GPIO as GPIO
import time
host = '192.168.0.198'
port = 9050
BUFFER_SIZE = 2000
MESSAGE = input("tcpClient1: Enter message/ Enter exit:")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while MESSAGE != 'exit':
s.send(str.encode(MESSAGE))
data = s.recv(BUFFER_SIZE)
data = data.decode('utf-8')
print (" Client2 received data:", data)
MESSAGE = input("tcpClient2: Enter message to continue/ Enter exit:")
client2 code:
import socket
import RPi.GPIO as GPIO
import time
import socket
host = '192.168.0.198'
port = 9050
BUFFER_SIZE = 2000
MESSAGE = input("tcpClient2: Enter message/ Enter exit:")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
while MESSAGE != 'exit':
s.send(str.encode(MESSAGE))
data = s.recv(BUFFER_SIZE)
data = data.decode('utf-8')
print (" Client received data:", data)
MESSAGE = input("tcpClient2: Enter message to continue/ Enter exit:")
when i run, i obtain:
in the server terminal:
Multithreaded Python server : Waiting for connections from TCP clients...
[+] New server socket thread started for 192.168.0.197:47012
Multithreaded Python server : Waiting for connections from TCP clients...
[+] New server socket thread started for 192.168.0.196:47886
Multithreaded Python server : Waiting for connections from TCP clients...
in client1 terminal:
tcpClient1: Enter message/ Enter exit:begin
in client2 terminal:
tcpClient2: Enter message/ Enter exit:begin
It seems like server didn't receive or send any data.
As #Hikke mentioned in his comment, your server receives at two different places. The conn.recv call in this code snippet eats up the data that the server receiving thread is expecting. Remove data = conn.recv(2048) in your server's main loop:
while True:
print ("Multithreaded Python server : Waiting for connections from TCP clients...")
(conn, (ip,port)) = s.accept()
data = conn.recv(2048) # <== dont eat the data of your thread here!
newthread = ClientThread(ip,port)
newthread.start()
threads.append(newthread)
list_data.append(data)

Resources