Este artigo apresenta o caso de transferência de arquivos baseado em soquete Java e é compartilhado com você para sua referência. O conteúdo específico é o seguinte
1. Código Java
pacote com.wf.demo.socket.socketfile; importar java.net.*; importar java.io.*; / * * private int porta; soquete privado soquete = nulo; DataOutputStream Out = null; DatainputStream getMessaGestream = null; public clientsocket (string ip, porta int) {this.ip = ip; this.port = porta; } / ** * Crie conexão de soquete * * @THOWSOWS Exceção * Exceção * / public void createConnection () lança Exceção {try {Socket = new Socket (IP, porta); } catch (Exceção e) {e.printStackTrace (); if (soquete! = NULL) soquete.close (); jogar e; } finalmente {}} // Envie uma mensagem pública void sendMessage (string sendMessage) lança Exceção {try {out = new DataOutputStream (soket.getOutputStream ()); if (sendMessage.equals ("windows")) {out.writebyte (0x1); out.flush (); retornar; } if (sendMessage.equals ("unix")) {out.writebyte (0x2); out.flush (); retornar; } if (sendMessage.equals ("linux")) {out.writebyte (0x3); out.flush (); } else {out.writeutf (sendMessage); out.flush (); }} catch (Exceção e) {e.printStackTrace (); if (out! = null) out.close (); jogar e; } finalmente {}} // Aceite a mensagem public DatainputStream getMessaGestream () lança Exceção {try {getMessageStream = new DataAinputStream (new bufferInputStream (Socket.getInputStream ()); retornar getMessaGeStream; } catch (Exceção e) {e.printStackTrace (); if (getMessageStream! = null) getMessaGESTREAM.CLOSE (); jogar e; } finalmente {}} // Feche a conexão public void ShutdownConnection () {try {if (out! = null) out.close (); if (getMessageStream! = null) getMessaGESTREAM.CLOSE (); if (soquete! = NULL) soquete.close (); } catch (Exceção e) {}}} 2. Código Java
pacote com.wf.demo.socket.socketfile; importar java.io.bufferInputStream; importar java.io.datainputStream; importar java.io.dataOutputStream; importar java.io.file; importar java.io.fileInputStream; importar java.net.serversocket; importar java.net.socket; / ** * 1. Lado do servidor * * @Author Willson * */ classe pública servertest {int porta = 8821; void start () {soquete de soquete = null; tente {serverSocket ServerSocket = new ServerSocket (porta); while (true) {// selecione o arquivo para transferência string filepath = "e: //lib.zip"; Arquivo fi = novo arquivo (filepath); System.out.println ("Nome do arquivo:" + fi.getName () + ";/tfile size ():" + (int) fi.length () + "bytes"); // Public Socket Accept () lança // ioexception escuta e aceita conexões com este soquete. Este método bloqueia até que a conexão seja feita. System.out.println ("Aguardando o cliente conectar, porta de conexão:" + porta); soquete = serversocket.accept (); System.out.println ("Criar link de soquete"); DatainputStream Dis = new DataAinputStream (new BufferInputStream (Socket.getInputStream ()); Dis.readByte (); DatainputStream fis = new DataAinputStream (new BufferInputStream (new FileInputStream (FilePath))); DataOutputStream ps = new DataOutputStream (Socket.getOutputStream ()); // Passe o nome do arquivo e o comprimento para o cliente. Para se aplicar verdadeiramente a todas as plataformas, como o processamento de nomes chineses, ele também precisa ser processado. Para detalhes, consulte o pensamento em java // há código pronto no 4º. ps.Writeutf (fi.getName ()); ps.flush (); Ps.Writelong ((Long) fi.Length ()); ps.flush (); int buffersize = 8192; byte [] buf = novo byte [buffersize]; while (true) {int read = 0; if (fis! = null) {read = fis.read (buf); } if (read == -1) {break; } ps.write (buf, 0, leia); } ps.flush (); // Preste atenção no fechamento do link do soquete, caso contrário, o cliente aguardará os dados do servidor, // até o tempo limite do soquete, resultando em dados incompletos. fis.close (); Socket.Close (); System.out.println ("Transferência de arquivos concluída/n"); }} catch (Exceção e) {e.printStackTrace (); }} public static void main (string arg []) {new servertest (). start (); }}
3. Cliente
pacote com.wf.demo.socket.socketfile; importar java.io.bufferedOutputStream; importar java.io.datainputStream; importar java.io.dataOutputStream; importar java.io.fileOutputStream; / ** * 3. Client * * @author Willson * */ public class ClientTest {private ClientSocket CS = NULL; private string ip = "localhost"; // defina como servidor IP private int porta = 8821; String privada sendMessage = "Windwos"; public clientTest () {try {if (createConnection ()) {sendMessage (); getMessage ("f: //"); }} catch (Exceção ex) {ex.PrintStackTrace (); }} private boolean createConnection () {cs = new CustomerSocket (IP, porta); tente {cs.createConnection (); System.out.print ("conectado ao servidor com sucesso!" + "/N"); retornar true; } catch (Exceção e) {System.out.print ("conectar ao servidor falhou!" + "/n"); retornar falso; }} private void sendMessage () {if (cs == null) return; tente {cs.sendMessage (sendMessage); } catch (Exceção e) {System.out.print ("Enviar a mensagem falhou!" + "/n"); }} private void getMessage (string savePath) {if (cs == null) return; DatainputStream inputStream = null; tente {inputStream = cs.getMessageStream (); } catch (Exceção e) {System.out.print ("Receba Erro de Cache da Mensagem/N"); retornar; } tente {// Caminho de salvamento local, o nome do arquivo herdará automaticamente do lado do servidor. int buffersize = 8192; byte [] buf = novo byte [buffersize]; int passedlen = 0; longo len = 0; savePath += inputStream.readUtf (); DataOutputStream fileout = new DataOutputStream (new BufferoudOutputStream (new BufferoudOutputStream (new FileOutputStream (SavePath)))); len = inputStream.readlong (); System.out.println ("size de arquivo ():" + len + "bytes"); System.out.println ("Comece a receber arquivos!" + "/N"); while (true) {int read = 0; if (inputStream! = null) {read = inputStream.read (buf); } passedlen += leia; if (read == -1) {break; } // A seguinte barra de progresso é feita da barra de progresso da interface gráfica. Se você estiver digitando um arquivo aqui, algumas das mesmas porcentagens poderão ser impressas repetidamente System.out.println ("arquivo recebido" + (passedlen * 100 / len) + "% / n"); fileout.write (buf, 0, leia); } System.out.println ("Recebido, arquivo salvo como" + salvath + "/n"); fileout.close (); } catch (Exceção e) {System.out.println ("Receba erro de mensagem" + "/n"); retornar; }} public static void main (string arg []) {new clientTest (); }}Espero que este artigo seja útil para que todos aprendam a programação Java.