与 python 服务器共享文件

Share files with python server

我正在 python 服务器上工作。我也已经创建了服务器和客户端。 服务器:

import socket, threading

class ClientThread(threading.Thread):

def __init__(self,ip,port):
    threading.Thread.__init__(self)
    self.ip = ip
    self.port = port
    print "[+] New thread started for "+ip+":"+str(port)

def run(self):    
    print "Connection from : "+ip+":"+str(port)
    stop = False
    while stop == False:
        try:
             data = clientsock.recv(2048)
             print "["+ip+"] : "+data
             clientsock.send("You sent me: "+data)
        except:
             stop = True
    print "[-] Close thread for  "+ip

host = "x.x.x.x"
port = 9999

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

tcpsock.bind((host,port))
threads = []


while True:
    tcpsock.listen(4)
    print "\nListening for incoming connections..."
    (clientsock, (ip, port)) = tcpsock.accept()
    newthread = ClientThread(ip, port)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()

客户:

import socket
import sys
HOST, PORT = "x.x.x.x", 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print " Connect to server !!"
msg='o'
while msg != "close":
    msg= raw_input("Ask user for something >>")
    sock.sendall(msg)
    try:
        msg1 = sock.recv(2048)
    except:
        print"server closed"
        msg1='nothing !!'
        msg='close'
    print'server reply >' +msg1
    print""
print"just press enter"
raw_input()

现在我不仅要共享(在客户端和服务器之间)字符串变量的消息,还要共享一些文件。 例如,我要从客户端向服务器发送一个.jpg 文件。 关于我该怎么做的任何想法或建议?

非常感谢 Ajay,您找到了方法! 我搜索时没有看到您链接的 post! 我写下亲爱的 post 你指出的: Sending Txt file to server from client using python sockets