![](/img/trans.png)
[英]How to send data from client socket to server socket using Python?
[英]How to correctly send image through socket using python client and C server
我正在編寫類似聊天的應用程序,其中用戶除了發送消息之外還可以發送圖片。 唯一的問題是我不確定我應該如何處理圖像發送。 主要思想是用戶在控制台中選擇圖像寫入/send image.jpg
,然后通過socket.send(image.jpg)
發送圖像。 發送圖像對我來說很好,但是我的 C 服務器由於緩沖區而從單獨的“包”中從客戶端獲取數據輸入,但是當我添加它們時,它們與我的圖像大小不匹配(例如我的圖像是 73kb 但服務器從兩個單獨的“包”20kb + 8.5kb 中獲取 29kb)。 第二個問題是如何進一步發送這些數據,我認為也許有某種方法可以通過實際圖像二進制數據傳遞緩沖區並將其發送到 Python 中我的客戶的 rest。 我的緩沖區是 20480 字節。
從 client.py 發送:
elif "/send " in buffer:
fileArr = buffer.split(' ') #filearr = ["/send", "image.jpg"]
file = open(fileArr[1], "rb").read()
s.send(fileArr[0].encode()) #metadata that im sending image file
time.sleep(0.2)
s.send(file) #sending my file
time.sleep(1)
print("Image sent!")
我的 server.c 接收和發送:
void send_message(char *s, int uid){
pthread_mutex_lock(&clients_mutex);
for (size_t i = 0; i < MAX_CLIENTS; i++) {
if(clients[i]){
if(clients[i]-> uid != uid){
if(write(clients[i]->sockfd, s, strlen(s)) < 0){
perror("");
printf("Write to descriptor failed \n");
break;
}
}
}
}
pthread_mutex_unlock(&clients_mutex);
}
if(strstr(buffer, "/send") != NULL || receive > 128){
if(strstr(buffer, "/send")){
buffer[0] = '\0';
}
recv(cli->sockfd, buffer, sizeof(buffer), 0); // Receiving my image and saving it to buffer
printf("receiveing img");
send_message(buffer, cli->uid); // Sending my buffer further to client
printf("sending image\n" );
而我的 client.py 接收:
def recvDataLoop():
while True:
reply = s.recv(buffer_sz)
if reply:
print("Got reply");
flag = 0
try:
reply = reply.decode()
if flag != 1 and "joined the chat" in reply or "has left" in reply:
print(reply)
elif flag != 1 and "|" in reply:
replyArr = reply.split("|")
time.sleep(0.1)
print("{}: {}".format(replyArr[0],replyArr[1]))
except:
print("Encoded") #If data received and it cannot be decoded, its <bytes>
try:
f = open("cat4.jpg", "ab").write(reply) #If image exists, write data to existing image
except:
f = open("cat4.jpg", "wb").write(reply)
我需要制作這個 try-except 塊,因為當接收到數據時,它是在包中接收的,所以當我得到它時,我需要將它寫入 cat4.jpg 文件的末尾。
套接字 rx/tx 函數通常返回實際傳輸的字節數。 因此,執行 rx/tx 的正確方法是在循環中調用 function,同時累積返回值並移動緩沖區起始指針。 此外,在處理二進制數據時 - 例如圖像數據 - null 終止假設是錯誤的,並且會截斷錯誤長度的數據; 它還可能觸發數組索引越界相關異常。 您需要明確指定 rx/tx 字節數( strlen
是錯誤的)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.