用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!
程序分Server和Client
站在用户的角度思考问题,与客户深入沟通,找到龙华网站设计与龙华网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:网站设计、成都网站建设、企业官网、英文网站、手机端网站、网站推广、空间域名、虚拟主机、企业邮箱。业务覆盖龙华地区。
服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Server.java代码如下:
/*
* 创建日期 2009-3-7
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
package faue.MutiUser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 服务器端
*
* @author Faue
*/
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
/**
* 构造方法,用于实现连接的监听
*
* @throws IOException
*/
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = super.accept();
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socket.getPort()).start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socket.getPort()).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
/**
* 该类用于创建接收客户端发来的信息并显示的线程
*
* @author Faue
* @version 1.0.0
*/
class ClientMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/**
* 得到Socket的输入流
*
* @param s
* @throws IOException
*/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
.getInputStream(), "GBK"));
}
public void run() {
try {
while (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length());
inputStringBuffer.append(in.readLine());
System.out.println(getMsg(inputStringBuffer.toString()));
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
}
}
/**
* 构造显示的字符串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line;
}
}
/**
* 该类用于创建发送数据的线程
*
* @author Faue
* @version 1.0.0
*/
class ServerMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/**
* 得到键盘的输入流
*
* @param s
* @throws IOException
*/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(client.getOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(System.in));
}
public void run() {
try {
while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length());
outputStringBuffer.append(keyboardInput.readLine());
out.println(outputStringBuffer.toString());
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/*
* 创建日期 2009-3-7
*
*/
package faue.MutiUser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* 客户端
*
* @author Faue
*/
public class Client {
private Socket mySocket;
/**
* 创建线程的构造方法
*
* @param IP
* @throws IOException
*/
public Client(String IP) throws IOException {
try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocket.getPort()).start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocket.getPort()).start();
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Server.IP:" + IP
+ " port:10000 can not be Connected");
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
System.out.println("输入的IP地址错误");
}
}
/**
* 该类用于创建接收服务端发来的信息并显示的线程
*
* @author Faue
* @version 1.0.0
*/
class ServerMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/**
* 得到Socket的输入流
*
* @param s
* @throws IOException
*/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
.getInputStream(), "GBK"));
}
public void run() {
try {
while (!client.isClosed()) {
inputStringBuffer.delete(0, inputStringBuffer.length());
inputStringBuffer.append(in.readLine());
System.out.println(getMsg(inputStringBuffer.toString()));
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
System.exit(0);
}
}
/**
* 构造输入字符串
*
* @param line
* @return
*/
private String getMsg(String line) {
return client.toString() + " says:" + line;
}
}
/**
* 该类用于创建发送数据的线程
*
* @author Faue
* @version 1.0.0
*/
class ClientMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/**
* 得到键盘的输入流
*
* @param s
* @throws IOException
*/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(client.getOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(System.in));
}
public void run() {
try {
while (!client.isClosed()) {
outputStringBuffer.delete(0, outputStringBuffer.length());
outputStringBuffer.append(keyboardInput.readLine());
out.println(outputStringBuffer.toString());
}
out.println("--- See you, bye! ---");
} catch (IOException e) {
//e.printStackTrace();
System.out.println(client.toString() + " is closed!");
System.exit(0);
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
java中如何实现从客户端发送文件到服务器端?
服务器端源码:\x0d\x0aimport java.io.BufferedReader;\x0d\x0aimport java.io.File;\x0d\x0aimport java.io.FileNotFoundException;\x0d\x0aimport java.io.FileOutputStream;\x0d\x0aimport java.io.IOException;\x0d\x0aimport java.io.InputStream;\x0d\x0aimport java.io.InputStreamReader;\x0d\x0aimport java.net.ServerSocket;\x0d\x0aimport java.net.Socket;\x0d\x0a\x0d\x0a/**\x0d\x0a *\x0d\x0a * 文件名:ServerReceive.java\x0d\x0a * 实现功能:作为服务器接收客户端发送的文件\x0d\x0a *\x0d\x0a * 具体实现过程:\x0d\x0a * 1、建立SocketServer,等待客户端的连接\x0d\x0a * 2、当有客户端连接的时候,按照双方的约定,这时要读取一行数据\x0d\x0a * 其中保存客户端要发送的文件名和文件大小信息\x0d\x0a * 3、根据文件名在本地创建文件,并建立好流通信\x0d\x0a * 4、循环接收数据包,将数据包写入文件\x0d\x0a * 5、当接收数据的长度等于提前文件发过来的文件长度,即表示文件接收完毕,关闭文件\x0d\x0a * 6、文件接收工作结束\x0d\x0a\x0d\x0apublic class ServerReceive {\x0d\x0a \x0d\x0a public static void main(String[] args) {\x0d\x0a \x0d\x0a /**与服务器建立连接的通信句柄*/\x0d\x0a ServerSocket ss = null;\x0d\x0a Socket s = null;\x0d\x0a \x0d\x0a /**定义用于在接收后在本地创建的文件对象和文件输出流对象*/\x0d\x0a File file = null;\x0d\x0a FileOutputStream fos = null;\x0d\x0a \x0d\x0a /**定义输入流,使用socket的inputStream对数据包进行输入*/\x0d\x0a InputStream is = null;\x0d\x0a \x0d\x0a /**定义byte数组来作为数据包的存储数据包*/\x0d\x0a byte[] buffer = new byte[4096 * 5];\x0d\x0a \x0d\x0a /**用来接收文件发送请求的字符串*/\x0d\x0a String comm = null;\x0d\x0a\x0d\x0a/**建立socekt通信,等待服务器进行连接*/\x0d\x0a try {\x0d\x0a ss = new ServerSocket(4004);\x0d\x0a s = ss.accept();\x0d\x0a } catch (IOException e) {\x0d\x0a e.printStackTrace();\x0d\x0a }\x0d\x0a\x0d\x0a/**读取一行客户端发送过来的约定信息*/\x0d\x0a try {\x0d\x0a InputStreamReader isr = new InputStreamReader(s.getInputStream());\x0d\x0a BufferedReader br = new BufferedReader(isr);\x0d\x0a comm = br.readLine();\x0d\x0a } catch (IOException e) {\x0d\x0a System.out.println("服务器与客户端断开连接");\x0d\x0a }\x0d\x0a \x0d\x0a /**开始解析客户端发送过来的请求命令*/\x0d\x0a int index = comm.indexOf("/#");\x0d\x0a \x0d\x0a /**判断协议是否为发送文件的协议*/\x0d\x0a String xieyi = comm.substring(0, index);\x0d\x0a if(!xieyi.equals("111")){\x0d\x0a System.out.println("服务器收到的协议码不正确");\x0d\x0a return;\x0d\x0a }\x0d\x0a \x0d\x0a /**解析出文件的名字和大小*/\x0d\x0a comm = comm.substring(index + 2);\x0d\x0a index = comm.indexOf("/#");\x0d\x0a String filename = comm.substring(0, index).trim();\x0d\x0a String filesize = comm.substring(index + 2).trim();\x0d\x0a\x0d\x0a/**创建空文件,用来进行接收文件*/\x0d\x0a file = new File(filename);\x0d\x0a if(!file.exists()){\x0d\x0a try {\x0d\x0a file.createNewFile();\x0d\x0a } catch (IOException e) {\x0d\x0a System.out.println("服务器端创建文件失败");\x0d\x0a }\x0d\x0a }else{\x0d\x0a /**在此也可以询问是否覆盖*/\x0d\x0a System.out.println("本路径已存在相同文件,进行覆盖");\x0d\x0a }\x0d\x0a \x0d\x0a /**【以上就是客户端代码中写到的服务器的准备部分】*/\x0d\x0a\x0d\x0a/**\x0d\x0a * 服务器接收文件的关键代码*/\x0d\x0a try {\x0d\x0a /**将文件包装到文件输出流对象中*/\x0d\x0a fos = new FileOutputStream(file);\x0d\x0a long file_size = Long.parseLong(filesize);\x0d\x0a is = s.getInputStream();\x0d\x0a /**size为每次接收数据包的长度*/\x0d\x0a int size = 0;\x0d\x0a /**count用来记录已接收到文件的长度*/\x0d\x0a long count = 0;\x0d\x0a \x0d\x0a /**使用while循环接收数据包*/\x0d\x0a while(count
回答于 2022-12-11
java点对点传输文件代码
//在我电脑运行没问题,把E:/EKI.txt传送到D:/EKI.txt你可以换成其它文件
//先运行Server,然后client,共三个class有问题QQ23400262
package ch.socket.file;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static int port = 6789;
public static String host = "127.0.0.1";
private static ServerSocket server = null;
public void run() {
if (server == null) {
try {
// 1、新建ServerSocket实例
server = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("服务器启动...");
while (true) {
try {
// 2、访问ServerSocket实例的accept方法取得一个客户端Socket对象
Socket client = server.accept();
if (client == null)
continue;
new SocketConnection(client, "D:\\").start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server().start();
}
}
package ch.socket.file;
import java.io.*;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
private Socket client;
private boolean connected;
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public Client(String host, int port) {
try {
// 1、新建Socket对象
client = new Socket(host, port);
System.out.println("服务器连接成功!");
this.connected = true;
} catch (UnknownHostException e) {
this.connected = false;
close();
} catch (IOException e) {
System.out.println("服务器连接失败!");
this.connected = false;
close();
}
}
/**
* 将文件内容发送出去
*
* @param filepath
* 文件的全路径名
*/
public void sendFile(String filepath) {
DataOutputStream out = null;
DataInputStream reader = null;
try {
if (client == null)
return;
File file = new File(filepath);
reader = new DataInputStream(new BufferedInputStream(
new FileInputStream(file)));
// 2、将文件内容写到Socket的输出流中
out = new DataOutputStream(client.getOutputStream());
out.writeUTF(file.getName()); // 附带文件名
int bufferSize = 2048; // 2K
byte[] buf = new byte[bufferSize];
int read = 0;
while ((read = reader.read(buf)) != -1) {
out.write(buf, 0, read);
}
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
close();
} finally {
try {
reader.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭Socket
*/
public void close() {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client(Server.host, Server.port);
if (client.isConnected()) {
client.sendFile("E:\\EKI.txt");
client.close();
}
}
}
package ch.socket.file;
import java.net.Socket;
import java.io.*;
public class SocketConnection extends Thread{
private Socket client;
private String filepath;
public SocketConnection(Socket client, String filepath){
this.client = client;
this.filepath = filepath;
}
public void run(){
if(client == null) return;
DataInputStream in = null;
DataOutputStream writer = null;
try{
//3、访问Socket对象的getInputStream方法取得客户端发送过来的数据流
in = new DataInputStream(new BufferedInputStream(client.getInputStream()));
String fileName = in.readUTF(); //取得附带的文件名
if(filepath.endsWith("/") == false filepath.endsWith("\\") == false){
filepath += "\\";
}
filepath += fileName;
//4、将数据流写到文件中
writer = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(new File(filepath)))));
int bufferSize = 2048;
byte[] buf = new byte[bufferSize];
int read = 0;
while((read=in.read(buf)) != -1){
writer.write(buf, 0, read);
}
writer.flush();
System.out.println("数据接收完毕");
}catch(IOException ex){
ex.printStackTrace();
}finally{
try{
in.close();
writer.close();
client.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
java 文件上传的代码,尽量详细一点。。。
// 这是我写的一个方法,里面只需要传两个参数就OK了,在任何地方调用此方法都可以文件上传
/**
* 上传文件
* @param file待上传的文件
* @param storePath待存储的路径(该路径还包括文件名)
*/
public void uploadFormFile(FormFile file,String storePath)throws Exception{
// 开始上传
InputStream is =null;
OutputStream os =null;
try {
is = file.getInputStream();
os = new FileOutputStream(storePath);
int bytes = 0;
byte[] buffer = new byte[8192];
while ((bytes = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytes);
}
os.close();
is.close();
} catch (Exception e) {
throw e;
}
finally{
if(os!=null){
try{
os.close();
os=null;
}catch(Exception e1){
;
}
}
if(is!=null){
try{
is.close();
is=null;
}catch(Exception e1){
;
}
}
}
}
当前文章:java传输文件代码 java文件传输接口
链接分享:http://scgulin.cn/article/dopgiep.html