服务端
package threadchat;
import java.net.*;
import java.io.*;
import java.util.concurrent.*;
import java.util.*;
import javax.swing.*;
public class Threadchat {
//private static final int buffer_size = 128;
private static final int thread_num = 10;
private static JFileChooser fileChooser=new JFileChooser("E:\\");//声明一定要写在这里,否则弹窗无法显示在最前面!!!!!
private static Socket socket=null;
public static void main(String[] args) throws Exception
{
final ServerSocket server = new ServerSocket(6789);
try{
System.out.println("Server has started!!!!");
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(thread_num);
for(int i=0;i<thread_num;i++)
{
fixedThreadPool.execute(new Runnable(){
public void run()
{
try{
while(true){
// receiveFile();
System.out.println("Waiting from client connectting!!!");
// 阻塞等的客户端的连接
if(socket==null){
socket=server.accept();
Thread writerThread = new Thread(new MyServerWriter(socket));//创建客户端线程发送数据
writerThread.start();
}
// 客户端的地址信息
SocketAddress address = socket.getRemoteSocketAddress();
System.out.println("Handling client at "+address+"\n");
//System.out.println("ininin");
// PrintWriter out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
// BufferedWriter out=new BufferedWriter(new OutputStreamWriter(
// new DataOutputStream(socket.getOutputStream()), "UTF-8"));
// OutputStreamWriter out=new OutputStreamWriter(
// new DataOutputStream(socket.getOutputStream()), "UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//System.out.println("ininin");
String judge=in.readLine();//读取字符串判断是发送字符串还是传文件
//System.out.println("ininin");
if(judge.equals("0"))//收到0处理接收和发送字符串
{
//System.out.println("ininin");
String str;
while((str = in.readLine()) != null)
{
//out.println(str);
//out.flush();
System.out.println("From client:"+str);
if(str.equals("exit"))
break;
}
//out.close();
//in.close();
//socket.close();
}
else if(judge.equals("1")){
String filename=in.readLine();//读取文件名
System.out.println("文件名:"+filename);
//receiveFile(socket,filename);
receiveFile(filename);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
});
}
}catch(Exception e){
if(server!=null){
server.close();
}
if(socket!=null)
socket.close();
e.printStackTrace();
}
}
public static void receiveFile(/*Socket socket,*/String filename) throws IOException {
byte[] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
ServerSocket server1=new ServerSocket(5209);
// DataOutputStream outToServer=null;
try {
String savePath;
Socket socket=server1.accept();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设置只能选择文件夹位置
// System.out.println("?????");
int returnVal = fileChooser.showOpenDialog(fileChooser);
// System.out.println("!!!");
if(returnVal==JFileChooser.APPROVE_OPTION)
{
// outToServer = new DataOutputStream(socket.getOutputStream());
//outToServer.writeBytes("请发送文件!"+'\n'); //发送一个字符串表示可以进行文件发送了,服务端已经准备好接收了
savePath=fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的绝对路径
dis = new DataInputStream(socket.getInputStream());
//文件储存位置就是下面
// File f = new File(savePath);
// if(!f.exists()){
// f.mkdir();
// }
/*
* 文件存储位置
*/
fos = new FileOutputStream(new File(savePath+"\\"+filename)); //文件输出流
//System.out.println("!!!");
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
outToServer.println("ready!"); //发送一个字符串表示准备好接收了
inputByte = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
//System.out.println(inputByte);
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收:"+filename);
}
else{
System.out.println("取消接收!!!");
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
// if (socket != null)
// socket.close();
if(server1!=null)
server1.close();
}
}
}
class MyServerWriter implements Runnable {//新建类用来发送数据
private static Socket socket = null;
// private static PrintWriter printWriter;
private static Scanner scanner=new Scanner(System.in);
private static JFileChooser fileChooser=new JFileChooser("E:\\");//声明一定要写在这里,否则弹窗无法显示在最前面!!!!!
public MyServerWriter(Socket clientsocket) throws IOException {
socket = clientsocket;
scanner = new Scanner(System.in);
// printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
}
@Override
public void run() {
try{
while(true){
System.out.println("请输入操作类型:0 发送字符串;1 上传文件;2 退出");
String a=scanner.next();
if(a.equals("0")){//发送字符串
chat();
}else if(a.equals("1")){//发送文件
uploadfile();
}else if(a.equals("2")){
scanner.close();
break;
}else{
System.out.print("输入错误,请重新输入!!!");
continue;
}
}
}catch(Exception e){
if(scanner!=null){
scanner.close();
}
e.printStackTrace();
}
}
public static void chat() throws IOException
{
String sentence;
//String modifiedSentence;
Socket clientSocket =socket;
try{
// BufferedReader inFromUser =
// new BufferedReader(new InputStreamReader(System.in));
//DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
PrintWriter outToServer=new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
// BufferedWriter outToServer=new BufferedWriter(new OutputStreamWriter(
// clientSocket.getOutputStream(), "UTF-8"));
// OutputStreamWriter outToServer=new OutputStreamWriter(
// new DataOutputStream(clientSocket.getOutputStream()), "UTF-8");
// BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.println("0"); //发送一个0表示进行的是字符串的发送
while(true){
//sentence = inFromUser.readLine();
System.out.println("请输入要发送的字符串:");
sentence = scanner.next();
if(sentence.length()==0) continue;
outToServer.println(sentence);
//modifiedSentence = inFromServer.readLine();
//System.out.println("FROM SERVER: " + modifiedSentence);
if(sentence.equals("exit")) break;
}
//outToServer.close();
//inFromServer.close();
//sc.close();
//clientSocket.close();
}catch(IOException e){
System.out.print("服务端连接异常!!!");
e.printStackTrace();
}
}
public static void uploadfile() throws Exception {
int length = 0;
double sumL = 0 ;
byte[] sendBytes = null;
Socket clientSocket = socket;
Socket socket2=null;//创建新连接来传输文件
DataOutputStream dos = null;
FileInputStream fis = null;
PrintWriter outToServer=null;
BufferedReader inFromServer=null;
// BufferedWriter outToServer=null;
boolean bool = false;
try {
// dos = new DataOutputStream(clientSocket.getOutputStream());
outToServer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
outToServer.println("1"); //发送一个1表示进行的是文件的发送
// outToServer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
//inFromServer=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String filePath;
//弹出选择文件框
//JFileChooser fileChooser = new JFileChooser("E:\\");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//设置只能选择文件
//System.out.println("???");
int returnVal = fileChooser.showOpenDialog(fileChooser);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
filePath= fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的绝对路径
System.out.println(filePath);
File file = new File(filePath); //你要传输的文件路径
String filename=file.getName();//获取文件名
//String fileType=filename.substring(filename.lastIndexOf("."));//获取文件后缀
//System.out.println(fileType);
System.out.println(filename);
outToServer.println(filename); //发送文件名
//outToServer.println(fileType); //发送文件后缀
//inFromServer.readLine();//等待服务端接收到文件名并返回一个信息,防止沾包
socket2=new Socket("127.0.0.1",5209);//创建新连接来传输文件,一定要在服务端创建等待连接后,所以要放在这里
dos = new DataOutputStream(socket2.getOutputStream()); //通过另一个连接发送文件内容
inFromServer=new BufferedReader(new InputStreamReader(socket2.getInputStream()));
inFromServer.readLine();//等待服务返回一个信息,表示已经选好存储地址并准备好接收了
long l = file.length();
fis = new FileInputStream(file);
sendBytes = new byte[1024];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
sumL += length;
System.out.println("已传输:"+((sumL/l)*100)+"%");
dos.write(sendBytes, 0, length);
dos.flush();
}
//虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较
if(sumL==l){
bool = true;
}
}
}catch (Exception e) {
System.out.println("客户端文件传输异常");
bool = false;
e.printStackTrace();
if(outToServer!=null){
outToServer.close();
}
// if(inFromServer!=null)
// {
// inFromServer.close();
// }
if (dos != null)
dos.close();
if (fis != null)
fis.close();
// if (clientSocket != null)
// clientSocket.close();
}finally{
if(socket2!=null)
socket2.close();
}
System.out.println(bool?"成功":"失败");
}
}
客户端
package chatclient;
//import java.awt.Desktop;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
//import threadchat.MyServerWriter;
public class Chatclient{
private static Scanner scanner=new Scanner(System.in);
private static JFileChooser fileChooser=new JFileChooser("E:\\");//声明一定要写在这里,否则弹窗无法显示在最前面!!!!!
private static Socket socket = null;
public static void main(String argv[]) throws Exception
{
try{
if(socket==null){
socket = new Socket("127.0.0.1", 6789);//建立连接
new Thread(new MyClientWriter(socket)).start();//创建服务器线程接收数据
}
while(true){
System.out.println("请输入操作类型:0 发送字符串;1 上传文件;2 退出");
String a=scanner.next();
if(a.equals("0")){//发送字符串
chat();
}else if(a.equals("1")){//发送文件
uploadfile();
}else if(a.equals("2")){
scanner.close();
break;
}else{
System.out.print("输入错误,请重新输入!!!");
continue;
}
}
}catch(Exception e){
if(scanner!=null){
scanner.close();
}
if(socket!=null){
socket.close();
}
e.printStackTrace();
}
}
public static void chat() throws IOException
{
String sentence;
//String modifiedSentence;
Socket clientSocket = socket;
try{
// BufferedReader inFromUser =
// new BufferedReader(new InputStreamReader(System.in));
//DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
PrintWriter outToServer=new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
// BufferedWriter outToServer=new BufferedWriter(new OutputStreamWriter(
// clientSocket.getOutputStream(), "UTF-8"));
// OutputStreamWriter outToServer=new OutputStreamWriter(
// new DataOutputStream(clientSocket.getOutputStream()), "UTF-8");
// BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.println("0"); //发送一个0表示进行的是字符串的发送
while(true){
//sentence = inFromUser.readLine();
System.out.println("请输入要发送的字符串:");
sentence = scanner.next();
if(sentence.length()==0) continue;
outToServer.println(sentence);
// modifiedSentence = inFromServer.readLine();
// System.out.println("FROM SERVER: " + modifiedSentence);
if(sentence.equals("exit")) break;
}
//outToServer.close();
//inFromServer.close();
//sc.close();
//clientSocket.close();
}catch(IOException e){
System.out.print("服务端连接异常!!!");
e.printStackTrace();
}
}
public static void uploadfile() throws Exception {
int length = 0;
double sumL = 0 ;
byte[] sendBytes = null;
Socket socket1 = socket;
Socket socket2=null;//创建新连接来传输文件
DataOutputStream dos = null;
FileInputStream fis = null;
PrintWriter outToServer=null;
BufferedReader inFromServer=null;
// BufferedWriter outToServer=null;
boolean bool = false;
try {
// dos = new DataOutputStream(socket2.getOutputStream()); //通过另一个连接发送文件内容
outToServer = new PrintWriter(new OutputStreamWriter(socket1.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
outToServer.println("1"); //发送一个1表示进行的是文件的发送
// outToServer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));
// inFromServer=new BufferedReader(new InputStreamReader(socket1.getInputStream()));
String filePath;
//弹出选择文件框
//JFileChooser fileChooser = new JFileChooser("E:\\");
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//设置只能选择文件
//System.out.println("???");
int returnVal = fileChooser.showOpenDialog(fileChooser);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
filePath= fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的绝对路径
System.out.println(filePath);
File file = new File(filePath); //你要传输的文件路径
String filename=file.getName();//获取文件名
//String fileType=filename.substring(filename.lastIndexOf("."));//获取文件后缀
//System.out.println(fileType);
System.out.println(filename);
outToServer.println(filename); //发送文件名
//outToServer.println(fileType); //发送文件后缀
//inFromServer.readLine();//等待服务端接收到文件名并返回一个信息,防止沾包
socket2=new Socket("127.0.0.1",5209);//创建新连接来传输文件,一定要在服务端创建等待连接后,所以要放在这里
dos = new DataOutputStream(socket2.getOutputStream()); //通过另一个连接发送文件内容
inFromServer=new BufferedReader(new InputStreamReader(socket2.getInputStream()));
inFromServer.readLine();//等待服务返回一个信息,表示已经选好存储地址并准备好接收了
long l = file.length();
fis = new FileInputStream(file);
sendBytes = new byte[1024];
while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
sumL += length;
System.out.println("已传输:"+((sumL/l)*100)+"%");
dos.write(sendBytes, 0, length);
dos.flush();
}
//虽然数据类型不同,但JAVA会自动转换成相同数据类型后在做比较
if(sumL==l){
bool = true;
}
}
//socket2.close();
}catch (Exception e) {
System.out.println("客户端文件传输异常");
bool = false;
e.printStackTrace();
if(outToServer!=null){
outToServer.close();
}
if (dos != null)
dos.close();
if (fis != null)
fis.close();
// if(socket2!=null)
// socket2.close();
} finally{
if(socket2!=null)
socket2.close();
}
System.out.println(bool?"成功":"失败");
}
}
class MyClientWriter implements Runnable{//新建类用来接收数据和文件
private Socket socket = null;
// private PrintWriter printWriter;
// private Scanner scanner;
private static JFileChooser fileChooser=new JFileChooser("E:\\");//声明一定要写在这里,否则弹窗无法显示在最前面!!!!!
public MyClientWriter(Socket socket) throws IOException {
this.socket = socket;
// scanner = new Scanner(System.in);
// printWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
}
@Override
public void run() {
try{
while(true){
// receiveFile();
// System.out.println("Waiting from client connectting!!!");
// 阻塞等的客户端的连接
Socket socket1=socket;
// 客户端的地址信息
SocketAddress address = socket1.getRemoteSocketAddress();
System.out.println("Handling client at "+address+"\n");
//System.out.println("ininin");
// PrintWriter out = new PrintWriter(new OutputStreamWriter(socket1.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
// BufferedWriter out=new BufferedWriter(new OutputStreamWriter(
// new DataOutputStream(socket.getOutputStream()), "UTF-8"));
// OutputStreamWriter out=new OutputStreamWriter(
// new DataOutputStream(socket.getOutputStream()), "UTF-8");
BufferedReader in = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
//System.out.println("ininin");
String judge=in.readLine();//读取字符串判断是发送字符串还是传文件
//System.out.println("ininin");
if(judge.equals("0"))//收到0处理接收和发送字符串
{
//System.out.println("ininin");
String str;
while((str = in.readLine())!= null)
{
//out.println(str);
//out.flush();
System.out.println("From server:"+str);
if(str.equals("exit"))
break;
}
//out.close();
//in.close();
//socket1.close();
}
else if(judge.equals("1")){
String filename=in.readLine();//读取文件名
System.out.println(filename);
//receiveFile(socket1,filename);
receiveFile(filename);
}
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void receiveFile(/*Socket socket1,*/String filename) throws IOException {
byte[] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
//DataOutputStream outToServer=null;
ServerSocket server1=new ServerSocket(5209);
try {
String savePath;
Socket socket=server1.accept();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设置只能选择文件夹位置
// System.out.println("?????");
int returnVal = fileChooser.showOpenDialog(fileChooser);
// System.out.println("!!!");
if(returnVal==JFileChooser.APPROVE_OPTION)
{
// outToServer = new DataOutputStream(socket.getOutputStream());
// outToServer.writeBytes("请发送文件!"+'\n'); //发送一个字符串表示可以进行文件发送了,服务端已经准备好接收了
savePath=fileChooser.getSelectedFile().getAbsolutePath();//这个就是你选择的文件夹的绝对路径
dis = new DataInputStream(socket.getInputStream());
//文件储存位置就是下面
// File f = new File(savePath);
// if(!f.exists()){
// f.mkdir();
// }
/*
* 文件存储位置
*/
fos = new FileOutputStream(new File(savePath+"\\"+filename)); //文件输出流
//System.out.println("!!!");
PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()),true);//这里的true一定要加上,表示刷新缓冲区
outToServer.println("ready!"); //发送一个字符串表示准备好接收了
inputByte = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收:"+filename);
}
else{
System.out.println("取消接收!!!");
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
if (server1 != null)
server1.close();
}
}
}
代码写得太乱了,但是实在懒得改QAQ。