1
我正在一個python服務器上工作。我已經創建了服務器和客戶端。 服務器:與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文件。 關於我該如何做的任何想法或建議?
http://stackoverflow.com/questions/17501131/sending-txt-file-to-server-from-client-using-python-sockets – Ajay