package rgy.com.UDP3;

import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask; import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants; public class Client extends JFrame {
// 加入属性
private JPanel panel = new JPanel();
private JButton button_send = new JButton("文件发送");
private JButton button_receive = new JButton("另存为");
private JTextArea ta = new JTextArea();
private JScrollPane sp = new JScrollPane(ta);
private JTextArea ta_send = new JTextArea();
private JScrollPane sp_send = new JScrollPane(ta_send);
private JLabel label_fileState = new JLabel("文件状态", JLabel.CENTER);
private JLabel label_feedback = new JLabel("反馈", JLabel.CENTER);
//
private InetAddress ip = null;
private int otherport;
private int myport;
DatagramSocket socket;// 接收文件来显提示
DatagramSocket socket1;// 接收文件信息
DatagramSocket socket2;// 接收平时的聊天信息
//
String filename = null;
byte buffer[] = new byte[1024];
int fileLen = 0;
int numofBlock = 0;
int lastSize = 0;
//
String str_name; //
public Client(String str_name, String str_ip, int otherport, int myport) {
super(str_name);
this.str_name = str_name;
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(600, 250, 300, 400);
// 加入功能代码
this.setLayout(new GridLayout(5, 1, 7, 7));
ta.setLineWrap(true);// 换行
this.add(sp);
ta_send.setLineWrap(true);// 换行
this.add(sp_send);
button_send.setFont(new Font("楷体", 1, 20));
button_receive.setFont(new Font("楷体", 1, 20));
panel.add(button_send);
panel.add(button_receive);
this.add(panel);
this.add(label_fileState);
this.add(label_feedback);
//
this.setVisible(true);
//
this.otherport = otherport;
this.myport = myport;
//
button_send.addActionListener(new ActionListener() {// 发送文件
public void actionPerformed(ActionEvent e) {
// 选择要发送的文件
JFileChooser filechooser = new JFileChooser();
int result = filechooser.showOpenDialog(Client.this);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = filechooser.getSelectedFile();
try {
// 将文件名称发送过去
String str_filename = file.getName();
String str_tip = "有文件,请处理:" + str_filename;
byte[] fileNameBuf = str_tip.getBytes();
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(
fileNameBuf, fileNameBuf.length,
ip, Client.this.otherport);
socket.send(packet);
socket.close();
//
FileInputStream fis = new FileInputStream(
file);// 从文件里取出写入内存
// 将文件长度发送过去
int fileLen = fis.available();
String str_len = "" + fileLen;
byte[] fileLenBuf = str_len.getBytes();
socket = new DatagramSocket();
packet = new DatagramPacket(fileLenBuf,
fileLenBuf.length, ip,
Client.this.otherport+1);
socket.send(packet);
socket.close();
// 发送文件主体
byte[] buf = new byte[1024];
int numofBlock = fileLen / buf.length;// 循环次数(将该文件分成了多少块)
int lastSize = fileLen % buf.length;// 最后一点点零头的字节数
socket = new DatagramSocket();
for (int i = 0; i < numofBlock; i++) {
fis.read(buf, 0, buf.length);// 写入内存
packet = new DatagramPacket(buf,
buf.length, ip,
Client.this.otherport+1);
socket.send(packet);
Thread.sleep(1); // 简单的防止丢包现象
}
// 发送最后一点点零头
fis.read(buf, 0, lastSize);
packet = new DatagramPacket(buf,
buf.length, ip,
Client.this.otherport+1);
socket.send(packet);
Thread.sleep(1); // 简单的防止丢包现象
//
fis.close();
socket.close();
//
label_fileState.setText("文件传输完成。");
ta.append("");
//
} catch (Exception ev) {
System.out.println(ev);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Client.this,
"打开文档出错!");
}
}
}
});
// /////////////
button_receive.addActionListener(new ActionListener() {// 接收文件
public void actionPerformed(ActionEvent e) {
// 选择要接收的文件
JFileChooser filechooser = new JFileChooser();
int result = filechooser.showSaveDialog(Client.this);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file2 = filechooser.getSelectedFile();
try {
File file1 = new File("D:\\TT\\" + filename);
saveAs(file1, file2);
//
label_fileState.setText("文件接收完成! ");
ta.append("文件已处理!!\n");
} catch (Exception ex) {
System.out.println(ex);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(Client.this,
"打开保存出错!");
}
}
}
});
//
ta_send.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
String str_chat = Client.this.str_name + " 说: "
+ ta_send.getText();
byte buf[] = str_chat.getBytes();
if (ke.isControlDown() && ke.getKeyCode() == KeyEvent.VK_ENTER) {
try {
DatagramSocket socket = new DatagramSocket();
DatagramPacket packet = new DatagramPacket(buf,
buf.length, ip, Client.this.otherport+2);
socket.send(packet);
ta.append("我说: "+ta_send.getText()+"\n");
ta_send.setText("");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
});
//
try {
ip = InetAddress.getByName(str_ip);
socket = new DatagramSocket(this.myport);
socket1 = new DatagramSocket(this.myport + 1);
socket2 = new DatagramSocket(this.myport + 2);
Timer timer = new Timer();//定时器,刷新接收消息
timer.schedule(new MyTimerTask_receive(),0, 100);
while (socket!=null) {
try {
//
byte filetipBuf[] = new byte[256];// 防止文件名称字过长(此处最长256个字符)
DatagramPacket packet_tip = new DatagramPacket(filetipBuf,
0, filetipBuf.length);
socket.receive(packet_tip);
String str_filetip = new String(packet_tip.getData(), 0,
packet_tip.getLength());
filename = str_filetip.substring(8);
ta.append(str_filetip + "\n");
// 接收文件长度(字节数)
byte[] fileLenBuf = new byte[12];// 能够传输1T的文件
DatagramPacket packet_len = new DatagramPacket(fileLenBuf,
fileLenBuf.length);
socket1.receive(packet_len);
String str_fileLen = new String(fileLenBuf, 0,
packet_len.getLength());
fileLen = Integer.parseInt(str_fileLen);
ta.append("文件大小: " + fileLen + "字节, " + (fileLen / 1024)
+ "kb, " + (fileLen / 1024 / 1024) + "Mb\n");
//
DatagramPacket packet_file = new DatagramPacket(buffer, 0,
buffer.length);
numofBlock = fileLen / buffer.length;// 循环次数(将该文件分成了多少块)
lastSize = fileLen % buffer.length;// 最后一点点零头的字节数
File file = new File("D:\\TT\\" + filename);
FileOutputStream fos = new FileOutputStream(file);// 从内存取出存入文件
for (int i = 0; i < numofBlock; i++) {
packet_file = new DatagramPacket(buffer, 0,
buffer.length);
socket1.receive(packet_file);// 通过套接字接收数据
fos.write(buffer, 0, 1024);// 写入文件
}
// 接收最后一点点零头
packet_file = new DatagramPacket(buffer, 0, lastSize);
socket1.receive(packet_file);// 通过套接字接收数据
fos.write(buffer, 0, lastSize);// 写入文件
fos.close();
// 反馈包
} catch (Exception e) {
System.out.println(e);
}
}
} catch (Exception e) {
System.out.println(e);
}
} public void saveAs(File file1, File file2) {// 把file1另存为file2,并删掉file1
try {
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
byte buf[] = new byte[1024];
int len = 0;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
file1.delete();
} catch (Exception ex) {
System.out.println(ex);
}
} class MyTimerTask_receive extends TimerTask {
public void run() {
try{
byte chatBuf[] = new byte[512];
DatagramPacket packet_chat = new DatagramPacket(chatBuf, 0,
chatBuf.length);
socket2.receive(packet_chat);
String str_chat = new String(packet_chat.getData(), 0,
packet_chat.getLength());
ta.append(str_chat + "\n");
}catch(Exception ex){
System.out.println(ex);
}
}
} // ////////////////////////////////////////////////////
public static void main(String args[]) {
new Client("Mary", "127.0.0.2", 6000, 10000);
}
}

java UDP聊天与文件传输的更多相关文章

  1. Python3 网络通信 网络聊天室 文件传输

    Python3 网络通信 网络聊天室 文件传输 功能描述 该项目将实现一个文字和文件传输的客户端和服务器程序通信应用程序.它将传输和接收视频文件. 文本消息必须通过TCP与服务器通信,而客户端自己用U ...

  2. java基于P2P的聊天和文件传输实例

    用java的NIO技术编写的 1. 支持聊天功能 2. 拖拽文件能够实现文件传输功能.也能够是目录 3. 启动时能够选择server端或client端启动 4. 本人原创.学习NIO和java的网络通 ...

  3. android asmack 注册 登陆 聊天 多人聊天室 文件传输

    XMPP协议简介 XMPP协议(Extensible Messaging and PresenceProtocol,可扩展消息处理现场协议)是一种基于XML的协议,目的是为了解决及时通信标准而提出来的 ...

  4. 用Java开发局域网内文件传输软件遇到的一些问题

    项目地址:https://github.com/b84955189/FileTransfer 由于巨懒的我不太喜欢使用U盘操作文件,特此开发一个简易的文件传输程序. 目前仅限局域网内传输,后期会尝试写 ...

  5. Linux下聊天和文件传输软件

    全平台聊天软件 米聊 官网地址: http://www.miliao.com 潮信 官网地址: https://www.chaoxin.com

  6. Tftp文件传输服务器(基于UDP协议)

    一个简单的UDP服务端与客户端 服务端: from socket import * #创建套接字 udp_server = socket(AF_INET,SOCK_DGRAM) msg_server ...

  7. JAVA之旅(三十二)——JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用

    JAVA之旅(三十二)--JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用 GUI写到一半电脑系统挂了,也就算了,最多GUI还有一个提示框和实例, ...

  8. 循序渐进Java Socket网络编程(多客户端、信息共享、文件传输)

    目录[-] 一.TCP/IP协议 二.TCP与UDP 三.Socket是什么 四.Java中的Socket 五.基本的Client/Server程序 六.多客户端连接服务器 七.信息共享 八.文件传输 ...

  9. nc 局域网聊天+文件传输(netcat)

    nc 局域网聊天+文件传输 nc的全程是netcat,这个工具非常好用. 有时候我们需要在局域网内传送一些文本消息或者文件的时候,通常的做法是安装一些局域网通讯软件,然后来做.其实不必要这样,使用nc ...

随机推荐

  1. 扩展IHttpHandler

    前面提到当请求进入到IIS,IIS转发给ISAPI后会根据文件的后缀名来决定将请求转发给对应的处理程序进行处理,当然一大部分的处理都是交给了AspNet_ISAPI 了.但是,AspNet_ISAPI ...

  2. 网络测速命令--speedtest

    网络测速 speedtest-cli 顾名思义,这个命令为网络测速命令,基于Python编写,测试系统网络的上传下载速度,GitHub托管的项目地址,以下列出常见的用法 安装命令 pip instal ...

  3. css + 和 ~的区别

    <style type="text/css"> h1 + p { margin-top:50px; color:red; } </style> <p& ...

  4. 奇异值分解 SVD 的数学解释

    奇异值分解(Singular Value Decomposition,SVD)是一种矩阵分解(Matrix Decomposition)的方法.除此之外,矩阵分解还有很多方法,例如特征分解(Eigen ...

  5. jQuery-图片的放大镜显示效果方法封装

    (function($){ $.fn.jqueryzoom = function(options){ var settings = { xzoom: 200, //zoomed width defau ...

  6. python 3 廖雪峰博客笔记(三) 命令行模式与交互模式

    python 的代码一般保存为 .py结尾的文本文件格式 比如 add.py 里写下如下内容 100 + 200 执行 add.py有两种方式: 1. 命令行方式:将python代码写入脚本中执行 p ...

  7. 零基础入门学习Python(16)--序列!序列!

    前言 你可能发现了,小甲鱼把这个列表,元组,字符串放在一起讲是有道理的,它们有许多共同点: 都可以通过索引得到每一个元素 默认索引值总是从0开始 可以通过分片的方法得到一个范围内的元素的集合 有很多共 ...

  8. c++基础_字符串对比

    #include <iostream> #include <string.h> #include <algorithm> using namespace std; ...

  9. Adversarial Auto-Encoders

    目录 Another Approach: q(z)->p(z) Intuitively comprehend KL(p|q) Minimize KL Divergence How to comp ...

  10. 常见算法的python实现

    提到排序算法,常见的有如下几种:冒泡排序.选择排序.插入排序.快速排序.堆排序.归并排序.希尔排序:查找算法最常见二分查找.这些算法的时间复杂度如下: 算法名称 时间复杂度(一般情况) 冒泡排序 O( ...