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

📄 chatclient.java

📁 ChipChat实现的是局域网中的聊天功能
💻 JAVA
字号:
package com.itjob.chat;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ChatClient extends Frame {

	/**
	 * @param args
	 */
	private TextField tf;
	private TextArea ta;
	private Socket s;
	private DataOutputStream dos;
	private DataInputStream dis;
	private boolean isGetInputStream = false;

	public static void main(String[] args) {
		new ChatClient().launchFrame();
	}

	public void launchFrame() {
		tf = new TextField();
		ta = new TextArea();
		ta.setRows(10);
		ta.setEditable(false);
		this.add(tf, BorderLayout.SOUTH);
		this.add(ta, BorderLayout.NORTH);
		tf.addActionListener(new TFListener());
		this.setLocation(400, 300);
		this.setSize(300, 300);
		pack();
		this.setVisible(true);
		connectServer();
		new Thread(new AcceptMessage()).start();
		this.addWindowListener(new WindowAdapter() {

			@Override
			public void windowClosing(WindowEvent e) {
				try {
					dos.close();
					s.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				System.exit(0);
			}
		});
	}

	private class TFListener implements ActionListener {
		String str = null;

		public void actionPerformed(ActionEvent e) {
			str = tf.getText();
			//ta.append(str.trim() + "\n");
			sendMessage(str);
			tf.setText("");
		}

		private void sendMessage(String str) {
				try {
					dos.writeUTF(str);
					dos.flush();
				} catch (NullPointerException e){
					//e.printStackTrace();
					System.out.println("发送消息失败!服务器可能未启动1.");
					System.exit(0);
				} catch (IOException e) {
					//e.printStackTrace();
					System.out.println("发送消息失败!服务器可能未启动2.");
					//System.out.println(str);
				} catch (Exception e) {
					//e.printStackTrace();
					System.out.println("发送消息失败!服务器可能未启动3.");
				} 
		}
	}

	private class AcceptMessage implements Runnable {

		public void run() {
			acceptMessage();
		}

		private void acceptMessage() {
			String str = null;
			try {
				while(isGetInputStream){
					str = dis.readUTF();
					//System.out.println(str);//--
					ta.append(str+"\n");					
				}
			} catch (SocketException e){
				System.out.println("I closed!");
			} catch (IOException e) {			
				e.printStackTrace();
			}			
		}
		
	} 

	public void connectServer() {
		try {
			s = new Socket("127.0.0.1", 5555);
			dos = new DataOutputStream(s.getOutputStream());
			dis = new DataInputStream(s.getInputStream());
			this.isGetInputStream = true;
			System.out.println("connect success!");
		} catch (UnknownHostException e) {
			//e.printStackTrace();
			System.out.println("服务器没有启动!");
		} catch (ConnectException e) {
			//e.printStackTrace();
			System.out.println("连接失败!服务器未启动!");// --
			//System.exit(0);
		} catch (IOException e){
			e.printStackTrace();
		}
	}

}

⌨️ 快捷键说明

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