В этой статье представлена корпуса перевода файлов на основе сокетов Java и передается вам для вашей ссылки. Конкретный контент заключается в следующем
1. Java Code
пакет com.wf.demo.socket.socketfile; Импорт java.net.*; импортировать java.io.*; / ** * 2. 2. Утолпный класс Socket * * @author Willson * */ public class Clientsocket {Private String IP; частный порт int; Приватный сокет = null; DataOutputStream Out = null; DataInputStream getMessAgeStream = null; public clientsocket (String ip, int port) {this.ip = ip; this.port = порт; } / ** * Создать соединение сокета * * @Throws Exception * Exception * / public void createConnection () Throws Exception {try {socket = new Socket (ip, port); } catch (Exception e) {e.printstackTrace (); if (ocket! = null) ocket.close (); бросить E; } наконец {}} // Отправить сообщение public void sendmessage (string sendmessage) throws exection {try {out = new DataOutputStream (socket.getOutputStream ()); if (sendmessage.equals ("windows")) {out.writebyte (0x1); out.flush (); возвращаться; } if (sendmessage.equals ("unix")) {out.writebyte (0x2); out.flush (); возвращаться; } if (sendmessage.equals ("linux")) {out.writebyte (0x3); out.flush (); } else {out.writeutf (sendmessage); out.flush (); }} catch (Exception e) {e.printstackTrace (); if (out! = null) out.close (); бросить E; } наконец {}} // Принять сообщение public DataInputStream getMessAgeStream () Throws exception {try {getMessAgeStream = new DataInputStream (new BufferedInptReam (socket.getInputStream ())); вернуть GetMessAgeStream; } catch (Exception e) {e.printstackTrace (); if (getMessAgeStream! = null) getMessAgeStream.close (); бросить E; } наконец {}} // Закройте соединение public void shutdownconcection () {try {if (out! = null) out.close (); if (getMessAgeStream! = null) getMessAgeStream.close (); if (ocket! = null) ocket.close (); } catch (Exception e) {}}} 2. код Java
пакет com.wf.demo.socket.socketfile; Импорт java.io.bufferedinputstream; импортировать java.io.datainputstream; импортировать java.io.dataoutputstream; Импорт java.io.file; импортировать java.io.fileinputstream; импортировать java.net.serversocket; импортировать java.net.socket; / ** * 1. Серверная сторона * * @author willson * */ public class servertest {int port = 8821; void start () {сокет сокет = null; try {serversocket serversocket = new Serversocket (порт); while (true) {// выберите файл для передачи строки filepath = "e: //lib.zip"; Файл fi = новый файл (filePath); System.out.println ("Имя файла:" + fi.getName () + ";/tfile size ():" + (int) fi.length () + "Bytes"); // public Socket Accept () Throws // ioException прослушивает и принимает соединения с этим сокетом. Этот метод блокирует до тех пор, пока соединение не будет сделано. System.out.println («В ожидании подключения клиента, порт подключения:« + порт); сокет = serversocket.accept (); System.out.println ("Создать линию сокета"); DataInputStream dis = new DataInputStream (New BufferedInputStream (socket.getInputStream ())); dis.readbyte (); DataInputStream fis = new DataInputStream (New BufferedInputStream (new FileInputStream (filePath))); DataOutputStream PS = новый DataOutputStream (socket.getOutputStream ()); // передавать имя файла и длину клиенту. Чтобы по -настоящему применяться ко всем платформам, таким как обработка китайских имен, это также необходимо обработать. Для получения подробной информации, пожалуйста, обратитесь к Java // Есть готовый код в 4-м. ps.writeutf (fi.getName ()); ps.flush (); ps.writelong ((long) fi.length ()); ps.flush (); int buffersize = 8192; byte [] buf = new Byte [buffersize]; while (true) {int Read = 0; if (fis! = null) {read = fis.read (buf); } if (read == -1) {break; } ps.write (buf, 0, read); } ps.flush (); // Обратите внимание на закрытие ссылки сокета, иначе клиент будет ждать, пока данные сервера будут появиться, // до тайм -аута сокета, что приведет к неполным данным. fis.close (); Socket.Close (); System.out.println ("Передача файла завершена/n"); }} catch (Exception e) {e.printstackTrace (); }} public static void main (string arg []) {new servertest (). start (); }}
3. Клиент
пакет com.wf.demo.socket.socketfile; Импорт java.io.bufferedOutputStream; импортировать java.io.datainputstream; импортировать java.io.dataoutputstream; Импорт java.io.fileOutputStream; / ** * 3. Клиент * * @author Willson * */ public Class ClientTest {private Clientsocket cs = null; Private String IP = "LocalHost"; // Установить на сервер IP private int port = 8821; частная строка sendmessage = "windwos"; public clienttest () {try {if (createConnection ()) {sendmessage (); getMessage ("f: //"); }} catch (Exception ex) {ex.printstackTrace (); }} private boolean createConnection () {cs = new Clientsocket (ip, port); try {cs.createconnection (); System.out.print ("успешно подключен к серверу!" + "/N"); вернуть истину; } catch (Exception e) {System.out.print ("Подключение к серверу не удалось!" + "/n"); вернуть ложь; }} private void sendmessage () {if (cs == null) return; try {cs.sendmessage (sendmessage); } catch (Exception e) {System.out.print ("Отправить сообщение не удалось!" + "/n"); }} private void getMessage (String savePath) {if (cs == null) return; DataInputStream inputStream = null; try {inputStream = cs.getMessAgeStream (); } catch (Exception e) {System.out.print ("Ошибка получения кэша сообщений/n"); возвращаться; } try {// локальный путь сохранения, имя файла будет автоматически наследовать со стороны сервера. int buffersize = 8192; byte [] buf = new Byte [buffersize]; int outderlen = 0; Long Len = 0; savePath += inputStream.readutf (); DateOutputStream fileout = new DataOutputStream (New BufferedOutputStream (новый BufferedOutputStream (New FileOutputStream (savePath)))); len = inputstream.readlong (); System.out.println ("file size ():" + len + "bytes"); System.out.println ("Начать получение файлов!" + "/N"); while (true) {int Read = 0; if (inputstream! = null) {read = inputstream.read (buf); } outedlen += Read; if (read == -1) {break; } // Следующий панель прогресса сделан из BrogressBar графического интерфейса. Если вы набираете здесь файл, некоторые из тех же процентов могут быть неоднократно распечатаны System.out.println («Файл получен» + (пропущенное * 100 / len) + "% / n"); fileout.write (buf, 0, read); } System.out.println ("получен, файл сохранен как" + savePath + "/n"); fileout.close (); } catch (Exception e) {System.out.println ("Ошибка получения сообщения" + "/n"); возвращаться; }} public static void main (string arg []) {new ClientTest (); }}Я надеюсь, что эта статья будет полезна всем, чтобы изучить Java -программирование.