Java Socket实现一对一聊天

客户端:

public class ClientFrame extends JFrame {
	
	
	private JTextArea textArea = new JTextArea();
	private SimpleDateFormat dateFormat;
	
	private PrintWriter writer;
	private BufferedReader reader;
	private Socket socket;
	
	public static void main(String[] args) {
		ClientFrame client = new ClientFrame();
		client.setVisible(true);
		client.connection();
	}


	public ClientFrame() {
		JScrollPane scrollPane = new JScrollPane();
		JTextField textField = new JTextField(20);
		JButton sendBtn = new JButton("发送");
		JButton emptyBtn = new JButton("清空历史消息");
		JButton exitBtn = new JButton("退出");
		JPanel panel = new JPanel();
		
		dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		JLabel dateLabel = new JLabel(dateFormat.format(new Date()), JLabel.CENTER);
		textArea.setEditable(false);
		textArea.setFont(new Font("宋体", 1, 15));
		this.setTitle("客户端");
		this.setSize(500, 400);
		this.setLocationRelativeTo(null);// 居中
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.getRootPane().setDefaultButton(sendBtn);
		this.setLayout(new BorderLayout());
		dateLabel.setForeground(Color.BLUE);
		dateLabel.setFont(new Font("", Font.BOLD, 22));
		this.add(dateLabel, BorderLayout.NORTH);
		this.add(scrollPane, BorderLayout.CENTER);
		scrollPane.setViewportView(textArea);
		this.add(panel, BorderLayout.SOUTH);
		panel.add(textField);
		panel.add(sendBtn);
		panel.add(emptyBtn);
		panel.add(exitBtn);

		sendBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {

				if (textField.getText().equals("")) {
					JOptionPane.showMessageDialog(null, "信息内容不能为空!", "提示", JOptionPane.ERROR_MESSAGE);
					return;
				}
				String info = textField.getText();
				dateFormat = new SimpleDateFormat("HH:mm:ss");
				textArea.append("客户端:" + dateFormat.format(new Date()) + "\n" + info + "\n");
				textField.setText("");
				writer.println(info);
			}
		});
		emptyBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if("".equals(textArea.getText())) {
					return;
				}
				Object yesORno[] = { "是", "否" };
				JOptionPane pane1 = new JOptionPane("确定清空消息记录吗?", JOptionPane.QUESTION_MESSAGE,
						JOptionPane.YES_NO_OPTION, null, yesORno, yesORno[0]);
				JDialog dialog = pane1.createDialog("提示");
				dialog.setVisible(true);
				Object selected = pane1.getValue();
				if (selected == null || selected == yesORno[1]) {
					// 如果否
				} else {// 是
					textArea.setText("");
				}
			}
		});
		exitBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
	}

	public void connection() {
		OutputStream os;
		InputStream is;
		InputStreamReader isr;
		try {
			String ip = JOptionPane.showInputDialog("IP地址");
			String port = JOptionPane.showInputDialog("端口号");
			socket = new Socket(ip, Integer.valueOf(port));
			while (true) {
				os = socket.getOutputStream();
				writer = new PrintWriter(os, true);
				is = socket.getInputStream();
				isr = new InputStreamReader(is);
				reader = new BufferedReader(isr);
				JOptionPane.showMessageDialog(null, "连接成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
				message();
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}

	public void message() {
		try {
			while (true) {
				if (reader != null) {
					String line = reader.readLine(); // 读取服务器发送的信息
					if (line != null) {
						dateFormat = new SimpleDateFormat("HH:mm:ss");
						textArea.append("服务端:" + dateFormat.format(new Date()) + "\n" + line + "\n");
					}
				}
			}
		} catch (Exception e) {
			textArea.append("服务端已退出。\n");
			JOptionPane.showMessageDialog(null, "服务端已退出!", "提示", JOptionPane.ERROR_MESSAGE);
		} finally {
			try {
				if (reader != null) {
					reader.close(); // 关闭流
				}
				if (socket != null) {
					socket.close(); // 关闭套接字
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

服务端:

public class ServerFrame extends JFrame {
	public static void main(String[] args) {
		ServerFrame server = new ServerFrame();
		server.setVisible(true);
		server.connection();
	}


	private JTextArea textArea = new JTextArea();

	private SimpleDateFormat dateFormat;
	private PrintWriter writer;
	private BufferedReader reader;
	private ServerSocket server;
	private Socket socket;

	public void connection() {
		try {
			String port = JOptionPane.showInputDialog("端口号");
			server = new ServerSocket(Integer.valueOf(port));
			while (true) {
				socket = server.accept();
				InputStream is = socket.getInputStream();
				InputStreamReader isr = new InputStreamReader(is);
				reader = new BufferedReader(isr);
				OutputStream os = socket.getOutputStream();
				writer = new PrintWriter(os, true);
				JOptionPane.showMessageDialog(null, "来自" + socket.getInetAddress().getHostAddress() + "的连接!", "提示",
						JOptionPane.INFORMATION_MESSAGE);
				message();
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}

	public void message() {
		dateFormat = new SimpleDateFormat("HH:mm:ss");
		try {
			while (true) {
				String line = reader.readLine();
				if (line != null) {
					textArea.append("客户端:" + dateFormat.format(new Date()) + "\n" + line + "\n");
				}
			}
		} catch (Exception e) {
			textArea.append("客户端已退出。\n");
			JOptionPane.showMessageDialog(null, "客户端已退出!", "提示", JOptionPane.ERROR_MESSAGE);
		} finally {
			try {
				if (reader != null) {
					reader.close();// 关闭流
				}
				if (socket != null) {
					socket.close(); // 关闭套接字
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public ServerFrame() {
		JScrollPane scrollPane = new JScrollPane();
		JTextField textField = new JTextField(20);
		JButton sendBtn = new JButton("发送");
		JButton emptyBtn = new JButton("清空历史消息");
		JButton exitBtn = new JButton("退出");
		JPanel panel = new JPanel();
		dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
		JLabel dateLabel = new JLabel(dateFormat.format(new Date()), JLabel.CENTER);
		textArea.setEditable(false);
		textArea.setFont(new Font("宋体", 1, 15));
		this.setTitle("服务端");
		this.setSize(500, 400);
		this.setLocationRelativeTo(null);// 居中
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.getRootPane().setDefaultButton(sendBtn);// 响应回车键
		this.setLayout(new BorderLayout());
		dateLabel.setForeground(Color.BLUE);
		dateLabel.setFont(new Font("", Font.BOLD, 22));
		this.add(dateLabel, BorderLayout.NORTH);
		this.add(scrollPane, BorderLayout.CENTER);
		scrollPane.setViewportView(textArea);
		this.add(panel, BorderLayout.SOUTH);
		panel.add(textField);
		panel.add(sendBtn);
		panel.add(emptyBtn);
		panel.add(exitBtn);

		sendBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (textField.getText().equals("")) {
					JOptionPane.showMessageDialog(null, "信息内容不能为空!", "提示", JOptionPane.ERROR_MESSAGE);
					return;
				}
				String info = textField.getText();
				dateFormat = new SimpleDateFormat("HH:mm:ss");
				textArea.append("服务端:" + dateFormat.format(new Date()) + "\n" + info + "\n");

				textField.setText("");
				writer.println(info);
			}
		});
		emptyBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if ("".equals(textArea.getText())) {
					return;
				}
				Object yesORno[] = { "是", "否" };
				JOptionPane pane1 = new JOptionPane("确定清空消息记录吗?", JOptionPane.QUESTION_MESSAGE,
						JOptionPane.YES_NO_OPTION, null, yesORno, yesORno[0]);
				JDialog dialog = pane1.createDialog("提示");
				dialog.setVisible(true);
				Object selected = pane1.getValue();
				if (selected == null || selected == yesORno[1]) {
					// 如果否
				} else {// 是
					textArea.setText("");
				}
			}
		});
		exitBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});
	}

}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值