大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
//以前写的一个文件传输的小程序,有客户端和服务器端两部分,服务器可//以一直运行,客户端传输完一个后退出,当然你也可以根据你的需要改。
10年积累的网站建设、网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先网站制作后付款的网站建设流程,更有宝兴免费网站建设让你可以放心的选择与我们合作。
//服务器端可以支持多个客户端同时上传,用到了多线程
/**
* 文件传输,客户端
* @aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file");
System.exit(0);
}
File file = new File(args[2]);
if(!file.exists() || !file.isFile()){
System.out.println("File \"" + args[2] + "\" does not exist or is not a normal file.");
System.exit(0);
}
Socket s = null;
FileInputStream in = null;
OutputStream out = null;
try{
s = new Socket(args[0], Integer.parseInt(args[1]));
in = new FileInputStream(file);
out = s.getOutputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
System.out.println("File tansfer statr...");
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
System.out.println("File tansfer complete...");
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
System.exit(1);
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
}catch(Exception e){}
}
}
}
/**
* 文件传输,服务器端
* @aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port");
System.exit(0);
}
ServerSocket ss = null;
try{
ss = new ServerSocket(Integer.parseInt(args[0]));
System.out.println("FtpServer start on port ..." + args[0]);
while(true){
Socket s = ss.accept();
new FtpThread(s).start();
System.out.println(s.getInetAddress().getHostAddress() + " connected.");
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(ss != null) ss.close();
}catch(Exception e){}
}
}
}
class FtpThread extends Thread{
Socket s;
long fileName = 0;
public FtpThread(Socket s){
this.s = s;
}
public void run(){
FileOutputStream out = null;
InputStream in = null;
File file = null;
do{
file = new File("" + (fileName++));
}while(file.exists());
try{
out = new FileOutputStream(file);
in = s.getInputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
System.out.println(s.getInetAddress().getHostAddress() + " connect closed..");
}catch(Exception e){}
}
}
}
//在我电脑运行没问题,把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();
}
}
}
}
// 这是我写的一个方法,里面只需要传两个参数就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里关于文件读写的有几十个类,不知道你想要如何实现,
以下是读文件的一个程序,如果有问题,发信息给我吧........
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;
public class javaTest {
public static void main(String[] args) {
String file1=System.getProperty("user.dir")+"/1.txt";//文件,自己修改
FileInputStream myFile = null;
try {
myFile = new FileInputStream(file1); //
} catch(FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel myChannel = myFile.getChannel();
//这里定义缓冲区大小,每次读入字节数
ByteBuffer mybuf = ByteBuffer.allocate(1024);
try {
while(myChannel.read(mybuf) != -1) {
byte[] mybytes = mybuf.array();//读入的文件转为字节数组
mybuf.clear();
/**
* 在这里进行比较
* 可以通过字节对比
* 也可以把字节转成字符串再对比
*
*/
}
myFile.close();
}catch(IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}
服务器端源码:\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
程序分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