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

📄 talkprogram.java

📁 Java的客户端服务器端的点对点通信程序
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
				System.exit(1);
			} catch (IOException e2) {
				System.out.println("");
			}
			// 清理
			finally {
				try {
					fis.close();
				} catch (IOException e3) {
					System.out.println("文件错误");
					System.exit(1);
				}
			}
		}
	}

	/*------------------------------------connect to server--------------------------------------------------*/
	class connect implements ActionListener {
		public void actionPerformed(ActionEvent e) {// 发送消息的实现

			try {
				
				//InetAddress addr = InetAddress.getLocalHost();
				
				//localIp=addr.getHostAddress().toString();
				
				//serverIP = conncetIp;
				PORT = SERVERPORT;
				
				socket = new DatagramSocket();// 建立对象
				System.out.println("connect successfully");
			} catch (SocketException e1) {
				System.err.println("Can't open socket");
				System.exit(1);
			//} catch (UnknownHostException e2) {
				// TODO 自动生成 catch 块
			//	e2.printStackTrace();
			}
		}
	}

	/*--------------------------------------client:send message --------------------------------------*/
	class SendMessage extends connect implements ActionListener {
		// 发送消息的实现

		public void actionPerformed(ActionEvent e) {
			try {
				// 构造数据报包,用来将包发送到指定主机上的指定端口号。

				System.out.println("Ip=" + serverIP);
				System.out.println("Port=" + PORT);
				DatagramPacket echo = Dgram.toDatagram(t1.getText(),
						InetAddress.getByName(serverIP), PORT);
				System.out.println("send message is used!");
				socket.send(echo);// 传送数据包
				String s = Dgram.toString(echo);
				// 时间的显示
				Calendar calendar = Calendar.getInstance();
				int hour = calendar.get(Calendar.HOUR_OF_DAY);
				int minute = calendar.get(Calendar.MINUTE);
				int second = calendar.get(Calendar.SECOND);
				ta1.append("自己:" + hour + "时" + minute + "分" + second + "秒:"
						+ "\n" + s + "\n" + "\n");
				// System.err.println("Send OK");

			} catch (IOException e1) {
				System.err.println("Communication error");
				e1.printStackTrace();
			}
			t1.setText(null);
		}
	}

	/*---------------------------------------close connection------------------------------------------*/
	class closeConnect extends connect implements ActionListener// close connect

	{
		public void actionPerformed(ActionEvent e) {
			ta1.append("connect is closed");
			socket.close();
		}
	}

	/*------------------------------------server:receive message ----------------------------------------*/
	class receiveMessage implements Runnable {
		private byte[] buf = new byte[1000];// 存放接受信息数组

		private DatagramPacket dp = new DatagramPacket(buf, buf.length);// 构造
																		// DatagramPacket,用来接收长度为
																		// length		
																	// 的数据包。

		private DatagramSocket socket;// DatagramSocket套接字

		String date;
		
	
		public void run() {// 有机会在虚拟cpu上执行的代码
			try {
				try {
					client = new Socket(serverIP, PORT);
				} catch (UnknownHostException e1) {
					// TODO 自动生成 catch 块
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO 自动生成 catch 块
					e1.printStackTrace();
				}
				socket = new DatagramSocket(SERVERPORT);
				System.out.println("Server started");
				while (true) {
					socket.receive(dp);// 阻塞等待连接,和client建立数据链路
					String rcvd = Dgram.toString(dp);// 将接收的包转化为字符串
					// 时间的显示
					Calendar calendar = Calendar.getInstance();
					int hour = calendar.get(Calendar.HOUR_OF_DAY);
					int minute = calendar.get(Calendar.MINUTE);
					int second = calendar.get(Calendar.SECOND);
					System.out.println("data=" + rcvd);
					ta1.append(user + ":" + hour + "时" + minute + "分" + second
							+ "秒:" + "\n" + rcvd + "\n" + "\n");
				}
			} catch (SocketException e) {// 异常处理
				System.err.println("Can't open socket");
				System.exit(1);
			} catch (IOException e) {
				System.err.println("Communication error");
				e.printStackTrace();
			}
		}
	}

	/*--------------------------------------server:receive file---------------------------------------*/
	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!");
			}
		}
	}

	/*-------------------------------------compress files-----------------------------------------*/

	/*-------------------------------client:send file--------------------------------------------*/
	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 = SERVERPORT;
					serverIP = conncetIp;
					// 通过打开一个到实际文件的连接来创建一个 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) {
				}
			}
		}
	}

	class send implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			try {
				sendFile send = new sendFile();// 启动server线程监听是否有人连接
				Thread td = new Thread(send);
				td.start();
			} catch (Exception e1) {
				System.out.println(" sendfile thread is error!");
			}
		}
	}

	/*------------------------------------------------------------------------------------------------------*/
	class stringlLeft implements KeyListener {
		String str, str1, str2;

		public void keyReleased(KeyEvent e) {
			int n = 20 - t1.getText().length();
			if (n >= 0) {
				str = String.valueOf(n);
				l4.setText("还可输入" + str + "个字符");
				str1 = t1.getText();
				System.out.println(str1);
			} else {
				t1.setText(str1);
			}
		}

		public void keyPressed(KeyEvent e1) {

		}

		public void keyTyped(KeyEvent e) {

		}

	}

	/*------------------------------Creates a new instance of TalkProgram ---------------------------------*/

	public static void main(String args[]) {

		new TalkProgram();
	}
}

⌨️ 快捷键说明

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