文档详情

socket多文件传输.docx

发布:2017-07-03约9.47千字共11页下载文档
文本预览下载声明
Socket多文件传输代码本文是一个多线程多文件传输实例,客户端里修改ip和port即可实现,代码是完整的。如果有不清楚的,可以给我留言。服务端代码:package com;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.RandomAccessFile;import java.net.ServerSocket;import java.net.Socket;public class FileServer implements Runnable {private static final int DEFAULT_PORT = 7778;private ServerSocket serverSocket;public final static int PER_RECEIVE_SIZE = 1024 * 100;/** * 启动程序 * * @param args */public static void main(String[] args) {FileServer server = new FileServer();server.init();Thread thread = new Thread(server);thread.start();}public void init() {try {serverSocket = new ServerSocket(DEFAULT_PORT);} catch (Exception e) {e.printStackTrace();}}public void run() {if (serverSocket == null) {System.out.println(ERROR);return;}while (true) {DataInputStream serverIn = null;DataOutputStream serverOut = null;Socket socket = null;try {socket = serverSocket.accept();serverIn = new DataInputStream(socket.getInputStream());serverOut = new DataOutputStream(socket.getOutputStream());while (true) {try {String command = readUTF(serverIn);if (command == null || !command.contains(ClientInfo)) {continue;}String fileName = new String(command.replaceAll((.+FileName|\\/FileName\\S+), ).toString().getBytes(UTF-8), UTF-8);String fileSize = new String(command.replaceAll((.+FileLength|\\/FileLength\\S+), ).toString().getBytes(UTF-8), UTF-8);String offset = new String(command.replaceAll((.+FilePointerStart|\\/FilePointerStart\\S+), ).toString().getBytes(UTF-8),UTF-8);String endset = new String(command.replaceAll((.+FilePointerEnd|\\/FilePointerEnd\\S+),).toString().getBytes(UTF-8), UTF-8);File tempFile = new File(E:\\socket, fileName + .temp);File parentFile = tempFile.getParentFile();boolean isCreate = initFile(tempFile, parentFile, Long.valueOf(fileSize));if (!isCreate) {closeSocket(serverIn, serverOut, socket);}String readyComma
显示全部
相似文档