程序分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
服務器端源碼:\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
//在我電腦運行沒問題,把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傳輸文件代碼 java文件傳輸接口
路徑分享:http://vcdvsql.cn/article48/dopgiep.html
成都網站建設公司_創新互聯,為您提供微信小程序、網站排名、定制開發、網站內鏈、外貿網站建設、Google
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯