用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用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 参考技术A //客户端
public class P2PClient
private TcpClient tcpClient;
//接受数据的线程
private Thread thMessageServer;
public delegate void ArrivedMsgListened(string receivedata);
public event ArrivedMsgListened TCPMsgArrived;
public void sendConnection(string serverIP, int portID)
tcpClient = new TcpClient();
//向服务器发起连接
tcpClient.Connect(serverIP,portID);
//开启接受线程
thMessageServer = new Thread(this.Receiver);
thMessageServer.Start();
//想服务器发送信息
public void Send(string sendMessage)
//得到TcpClient的网络流,此网络流就是一条发送数据的通道
NetworkStream stream = tcpClient.GetStream();
StreamWriter sw = new StreamWriter(stream);
//通过网络流向对方发送数据,记得调用Flush方法,数据才会发送到对方
sw.WriteLine(sendMessage);
sw.Flush();
//接受数据线程对应的方法
public void Receiver()
while (true)
//得到网络流以进行数据发送
NetworkStream stream = tcpClient.GetStream();
StreamReader sr=new StreamReader(stream);
//接受数据方法
string receivedata = sr.ReadLine();
TCPMsgArrived(receivedata);
参考技术B 我是这么认为的!说说,代码就请另想办法。java中传字符串和传文件的区别,不是太大的,都是流操作。传文件,就多一个文件名、传输结束等的判断,最好写一下简单的传输状态。
java实现多客户聊天功能
java 实现多客户端聊天(TCP),供大家参考,具体内容如下
- 编程思想:
1)、要想实现多客户端聊天,首先需要有多个客户端,而这些客户端需要随时发送消息和接受消息,所以收发消息需要放入不同的线程中。
2)、多客户聊天并不是多个客户之间进行两两通信,而是需要所有客户端与服务端进行交互,再由服务端统一下发信息到其他参与聊天的客户端。
- 代码实现:
2.1 实现专用于接收消息的子线程ReceiveThread
将接收消息和发送消息分为两个线程,其中将发送消息写入主线程中,开启新的线程用于接收消息。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class ReceiveThread extends Thread{
private Socket socket; //私有的成员变量,套接字
public ReceiveThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = null;//使用带缓冲区的字符输入流接收信息
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while(true){
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.2 客户端代码
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
@SuppressWarnings("all")
public static void main(String[] args) throws UnknownHostException, IOException {
//ip:需要连接的服务端所在的ip
//端口:客户端连接的端口必须和服务端端口一致
Socket socket = new Socket("192.168.*.*",8080);
Scanner scan = new Scanner(System.in);
new ReceiveThread(socket).start();
//发送给服务端信息
while(true ){
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("一号:"+scan.next());
}
}
}
注:
1)、客户端代码可以在局域网下的多台电脑上运行,只需要将ip地址改为服务端的ip,就能够连接。
2)、如果想要使用同台电脑完成一个服务端和两个客户端运行,进行测试多人聊天,可创建客户端2,使用本机ip
Socket socket = new Socket("127.0.0.1",8080);
Scanner scan = new Scanner(System.in);
new ReceiveThread(socket).start();
//发送给服务端信息
while(true ){
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("二号:"+scan.next());
}
2.3 服务端接收和转发信息的线程ServerThread
服务端在每一个客户端进行连接时,都会产生一个线程,用于服务这个客户,负责接收该客户发送的信息,并转发到参与多人聊天的其他客户。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Map.Entry;
import java.util.Set;
public class ServerThread extends Thread{
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
BufferedReader br = null;
String str=null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
while(true){
try {
str=br.readLine();
//在服务端输出,可以监测到所有人的聊天信息。
System.out.println(str);
//发送到其他客户端
Set<Entry<InetAddress, Socket>> entrySet = Server.map.entrySet();
for (Entry<InetAddress, Socket> entry : entrySet) {
InetAddress key = entry.getKey();
Socket value = entry.getValue();
if(socket.getInetAddress()!=key){
PrintStream printStream = new PrintStream(value.getOutputStream());
printStream.println(str);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.4 服务端代码
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
public class Server {
@SuppressWarnings("all")
public static ConcurrentHashMap<InetAddress, Socket> map =new ConcurrentHashMap<>();
public static void main(String[] args) throws IOException, InterruptedException {
//创建服务端的ServerSocket
ServerSocket server = new ServerSocket(8080);
while(true){
//接收到客户连接就创建一个对应的套接字
Socket socket = server.accept();
//获取该客户的ip
InetAddress inetAddress = socket.getInetAddress();
//将该客户的ip和套接字装入map集合
map.put(inetAddress, socket);
//创建新的线程服务该客户
new ServerThread(socket).start();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助
以上是关于用java多线程实现服务器与客户端之间的文件传输的代码!!!急!!!!的主要内容,如果未能解决你的问题,请参考以下文章