⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 myserver.java

📁 java简单算法
💻 JAVA
字号:
package server;

import dipImage.DispImage;
import java.net.*;
import java.io.*;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class MyServer extends Thread {

	ServerSocket serSocket; // 服务socket等待 对方的连接和文件发送
	Socket tempSocket;    // 由服务socket产生的socket
	InputStream inSocket; // 用于读取

	File savedFile = null;
	RandomAccessFile inFile = null;
	byte byteBuffer[] = new byte[1024];

	final int PORT = 4988; //设定服务器端口号

	public static void main(String args[]) {
		MyServer server = null;
		try {
			server = new MyServer(4988);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("无法传送文件!");
			System.exit(1);
		}
		server.start();

	}
	//--------------------开启服务器,选择保存文件位置----------------------------------------
	public MyServer(int port) throws Exception
	{
		try {

			serSocket = new ServerSocket(this.PORT);// 绑定服务的端口

		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Connected failed!");

		}
		JFileChooser jfc = new JFileChooser("./src");// 以当前的目录打开
		jfc.showSaveDialog(new javax.swing.JFrame());
		savedFile = jfc.getSelectedFile();       // 获取当前的选择文件引用
		if (savedFile != null)                 // 选择了文件
		{
			inFile = new RandomAccessFile(savedFile, "rw");// 用以读取数据的随机访问文件
		}
	}
//---------------判断传送的数据是否是图片----------------------------------
	boolean selectData(String str) {
		// 在每个空格字符处进行分解。
		String[] ss = str.toLowerCase().split("\\.");
		int length = ss.length;
		String s = ss[length - 1];
		if (s.equalsIgnoreCase("jpg") || s.equalsIgnoreCase("jpeg")
				|| s.equalsIgnoreCase("gif") || s.equalsIgnoreCase("bmp"))
			return true;
		else
			return false;
	}
	
//---------------------监听服务器端口,接收客户端发过来的数据---------------------------------------
	public void run() {
		try {
			if (this.inFile == null) {
				System.out.println("没有选择文件");
				this.serSocket.close();
				return; 
			}
			System.out.println("wait for..." + '\n' + "等待对方接入");
			tempSocket = serSocket.accept(); 

			this.inSocket = tempSocket.getInputStream();
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return;
		}
		int amount; 
		// 以下为传送文件代码 和清理工作
		try {
			while ((amount = inSocket.read(byteBuffer)) != -1) {
				inFile.write(byteBuffer, 0, amount);
			}
			inSocket.close(); // 关闭流
			JOptionPane.showMessageDialog(new javax.swing.JFrame(),
					"receive successfully!", "提示!",
					JOptionPane.PLAIN_MESSAGE);
			System.out.println("receive successfully!");
			//如果是图片,则显示
			if (selectData(savedFile.getName())) {
				new DispImage("显示图片", "src/" + savedFile.getName());
			}
			inFile.close();
			tempSocket.close();
			this.serSocket.close();
		} catch (IOException e) {
			System.out.println(e.toString());
			e.printStackTrace();
		}

	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -