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

📄 client5.java

📁 聊天功能,通过进入聊天介面可以和对方进行聊天
💻 JAVA
字号:

import java.awt.*;
import java.net.*;
import java.io.*;
import java.awt.event.*;
public class Client5 {
	private TextField nameBox = new TextField("(名字)");//显示用户名字
	private TextArea msgView = new TextArea();
	private TextField sendBox = new TextField();
	private BufferedReader reader;
	private PrintWriter writer;
	private Socket socket;
	public Client5(String title){
		super(title);
		msgView.setEditable(false);
		
		//添加组件
		add(nameBox,"North");
		add(msgView,"Center");
		add(sendBox,"South");
		
		//添加动作事件监听器
		sendBox.addActionListener(new ActionListener) 
		public void actionPerformed(ActionEvent ae) {
			try {
				//发送用户名及消息内容
				writer.println(nameBox.getText() + ":" + sendBox.getText());
				
				sendBox.setText("");//清除sendBox内容
			} catch(Exception ie){} 
		}
		pack();
		public void run() {
			while(true) {
				try {
					//从输入流读取数据,然后添加至msgView中
					msgView .append(reader.readLine() + "\n");
				} catch(IOException ie){}
			}
		}
		private void conncet() {
			try {
				msgView.append("尝试与服务器套接字连接\n");
				socket = new Socket("127.0.0.1",7777);
				msgView.append("聊天准备完毕\n");
				reader = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				writer = new PrintWriter(socket.getOutputStream(),true);
				new Thread(this).start();
			}catch(Exception e){
				msgView append("连接失败");
			}
		}
		public static void main(String[] args) {
			Client5 client = new Client5("聊天");
			client.setVisible(true);
			client.connect;
		}
	}
}

⌨️ 快捷键说明

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