Java网络聊天之文件传送

  这次带给大家的是Java Socket文件传送,给出核心代码:

  1.发送

 

class SendFile implements Runnable {
  public void run() {
   JFileChooser fc = new JFileChooser();
   int return_value = fc.showOpenDialog(b2);
   if (return_value == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    try {
     PORT = getPort(t3.getText());
     serverIP = getIP();
     // 通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象
     // file 指定。
     FileInputStream fos = new FileInputStream(file);
     Socket socket = new Socket(serverIP, PORT);// 创建连接到指定服务器的套接字
     socket.setSoTimeout(20);
     DataOutputStream out = new DataOutputStream(socket.getOutputStream());
     out.writeUTF(file.getName());// 以与机器无关方式使用 UTF-8  修改版编码将一个字符串写入基础输出流。
     ta1.append("File " + file.getName() + " begins to send!\n");
     OutputStream netOut = socket.getOutputStream();
     // BufferedOutputStream,该类实现缓冲的输出流。通过设置这种输出流,应用程序就可以将各个字节写入基础输出流中,而不必为每次字节写入调用基础系统。
     OutputStream doc = new DataOutputStream(new BufferedOutputStream(netOut));
     byte[] buf = new byte[2048];
     // 从此输入流中将最多 buf.length 个字节的数据读入一个字节数组中。
     int num = fos.read(buf);
     if (num != (-1))
      ta1.append("File is sending...\n");
     while (num != (-1))// 是否读完文件
     {
      doc.write(buf, 0, num);// 将指定字节数组中从偏移量0 开始的 num个字节写入基础输出流。
      doc.flush();// 清空此数据输出流。
      num = fos.read(buf);// 继续从文件中读取数据
     }
     if (num == (-1))
      ta1.append("The file sending is over.\n");
     fos.close();
     netOut.close();
     Thread.sleep(500);
    } catch (Exception ex) {
    }
   }
  }
 }

  2.接收

class ReceiveFile implements Runnable {
		// static final int INPORT1 = 8888;//端口号
		public void run() {
			try {
				ServerSocket server;
				server = new ServerSocket(SERVERPORT);
				// 创建绑定到特定端口的服务器套接字。
				Socket sock;// 创建一个Socket对象。服务器端便可以利用这个Socket对象与客户进行通讯。
				while (true) {
					sock = server.accept();// 侦听并接受到此套接字的连接
					InetAddress addr = sock.getInetAddress();// 返回套接字连接的地址。
					System.out.println(addr.getHostAddress());

					// 使用指定的基础 InputStream 创建一个 DataInputStream。
					DataInputStream infilename = new DataInputStream(sock.getInputStream());
					// 从流infilename中读取用 UTF-8 修改版格式编码的 Unicode 字符格式的字符串;然后以String 形式返回此字符串。
					String filename = new String(infilename.readUTF());
					System.out.println("filename=" + filename);
					ta1.append("File" + filename + " is from" + addr.getHostAddress() + "\n");
					File file = new File("C:" + filename);// 创建一个File实例
					// 当且仅当不存在具有此抽象路径名指定的名称的文件时,原子地创建由此抽象路径名指定的一个新的空文件。
					file.createNewFile();
					// 创建从中读取和向其中写入(可选)的随机存取文件流,该文件由 File 参数指定。
					RandomAccessFile raf = new RandomAccessFile(file, "rw");
					InputStream netIn = sock.getInputStream();// 返回此套接字的输入流。
					// BufferedInputStream(netIn),创建 BufferedInputStream
					// 并保存其参数,以便将来使用。
					DataInputStream in = new DataInputStream(
							new BufferedInputStream(netIn));
					byte[] buf = new byte[2048];
					// 从所包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 buf 中。
					int num = in.read(buf);
					if (num != (-1))
						ta1.append("File is sending...\n");
					while (num != (-1))// 是否读完所有数据
					{
						// 将 num 个字节从指定字节数组写入到此文件,并从偏移量 0处开始。
						raf.write(buf, 0, num);// 将数据写往文件
						// 尝试跳过输入的 num 个字节以丢弃跳过的字节。
						raf.skipBytes(num);// 顺序写文件字节
						num = in.read(buf);// 继续读取文件
					}
					if (num == (-1))
						ta1.append("The file has been saved to C disk" + "\n");
					in.close();
					raf.close();
				}
			} catch (Exception e) {
				System.out.println("receive error!");
			}
		}
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dimension ss = Toolkit.getDefaultToolkit().getScreenSize(); public ChatClient(){ super("登录聊天室"); pnlLogin = new JPanel(); this.getContentPane().add(pnlLogin); lblServer = new JLabel("服务器:"); lblPort = new JLabel("端口:"); lblName = new JLabel("用户名:"); lblPassword = new JLabel("口 令:"); tfServer = new JTextField(15); tfServer.setText("127.0.0.1"); tfPort = new JTextField(6); tfPort.setText("8000"); tfName = new JTextField(20); pwd = new JPasswordField(20); btnLogin = new JButton("登录"); btnRegister = new JButton("注册"); btnExit=new JButton("退出"); pnlLogin.setLayout(null); pnlLogin.setBackground(new Color(205,112,159)); lblServer.setBounds(40,35,50,30); tfServer.setBounds(90,35,102,25); lblPort.setBounds(195,35,35,30); tfPort.setBounds(230,35,55,25); lblName.setBounds(40,70,50,30); tfName.setBounds(90,70,195,25); lblPassword.setBounds(40,100,50,30); pwd.setBounds(90,100,195,25); btnLogin.setBounds(30,160,70,25); btnRegister.setBounds(130,160,70,25); btnExit.setBounds(230,160,70,25); pnlLogin.add(lblServer); pnlLogin.add(tfServer); pnlLogin.add(lblPort); pnlLogin.add(tfPort); pnlLogin.add(lblName); pnlLogin.add(tfName); pnlLogin.add(lblPassword); pnlLogin.add(pwd); pnlLogin.add(btnLogin); pnlLogin.add(btnRegister); pnlLogin.add(btnExit); //设置登录窗口 setResizable(false); setSize(320,260); setVisible(true); setLocation((ss.width-getWidth())/2,(ss.height-getHeight())/2); //为按钮注册监听 btnLogin.addActionListener(this); btnRegister.addActionListener(this); btnExit.addActionListener(this); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } //按钮监听响应 public void actionPerformed(ActionEvent ae){ Object source = ae.getSource(); if (source.equals(btnLogin)){ if (tfName.getText().equals("") || pwd.getPassword().equals("")) JOptionPane.showMessageDialog(null, "用户名或密码不能为空"); else strServerIp = tfServer.getText(); login(); } if (source.equals(btnRegister)){ strServerIp = tfServer.getText(); this.dispose(); new Register(strServerIp,8000); } if (source == btnExit) { System.exit(0); } } public void login() { User data = new User(); data.name = tfName.getText(); data.password = new String(pwd.getPassword()); try { String str = InetAddress.getLocalHost().toString(); data.ip = " "+ str.substring(str.lastIndexOf("/"), str.length()); } catch (UnknownHostException ex) { Logger.getLogger(ChatClient.class.getName()).log(Level.SEVERE, null, ex); } try{ Socket sock = new Socket(strServerIp,8000); ObjectOutputStream os = new ObjectOutputStream(sock.getOutputStream()); os.writeObject((User) data); //读来自服务器socket的登录状态 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream())); String status = br.readLine(); if (status.equals("登陆成功")){ new ChatRoom((String)data.name,strServerIp); this.dispose(); //关闭流对象 os.close(); br.close(); sock.close(); } else{ JOptionPane.showMessageDialog(null, status); os.close(); br.close(); sock.close(); } } catch (ConnectException e1){ JOptionPane.showMessageDialog(null, "连接到制定服务器失败!"); } catch (InvalidClassException e2) { JOptionPane.showMessageDialog(null, "类错误!"); } catch (NotSerializableException e3) { JOptionPane.showMessageDialog(null, "对象未序列化!"); } catch (IOException e4) { JOptionPane.showMessageDialog(null, "不能写入到指定服务器!"); } } public static void main(String arg[]){ new ChatClient(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值