📄 chatclient.java
字号:
package com.xdf.java.socket;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
/**
* 聊天室客户端
* <p>Title: 新东方Java book2</p>
*
* <p>Description: 这是课程的第二本书中的部分案例</p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: 新东方职业教育</p>
*
* @author hufoking
* @version 1.0
*/
public class ChatClient extends Frame{
TextArea ta=new TextArea(10,40);//消息接收显示框
TextField tf=new TextField(20);//消息编写框
TextField ipInput=new TextField("0.0.0.0",10);//IP输入框
TextField portInput=new TextField("6688",2);//输入端口
TextField nameInput=new TextField("Figo",5);//输入端口
Button conn=new Button("登录");
Button send=new Button("发送");//发送消息按钮
Socket client=null;
ChatClient win=this;
MyWindowlis mwlis=new MyWindowlis();
public ChatClient() {
super("聊天室客户端");
ta.setBackground(new Color(1,60,60));
ta.setForeground(Color.white);
ta.setEditable(false);
this.add(ta,BorderLayout.NORTH);
Panel p=new Panel();
p.add(new Label("IP"));
p.add(ipInput);
p.add(new Label("Port"));
p.add(portInput);
p.add(new Label("Name"));
p.add(nameInput);
p.add(conn);
p.add(tf);
p.add(send);
this.addWindowListener(mwlis);
this.add(p,BorderLayout.CENTER);
this.setResizable(false);//不能调节窗口大小
MyActionLis lis=new MyActionLis();
conn.addActionListener(lis);
send.addActionListener(lis);
tf.addActionListener(lis);
this.pack();
this.show();
}
public static void main(String[] args) {
ChatClient cc = new ChatClient();
}
private class MyWindowlis extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
//读服务器发过来的消息
private class ReadMsg extends Thread{
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
public void run(){
sendMsg("####"+nameInput.getText());
try {
is = client.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
String line = null;
while (true) {
while ((line = br.readLine()) != null) {
ta.append(line+"\n");
}
Thread.sleep(20);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
//发送消息
private void sendMsg(String msg) {
OutputStream os=null;
PrintStream ps=null;
try {
os = client.getOutputStream();
ps = new PrintStream(os);
ps.println(msg);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private class MyActionLis implements ActionListener{
//登录
private void logon() {
if (client == null || client.isClosed()) {
try {
client = new Socket(ipInput.getText(),Integer.parseInt(portInput.getText()));
ReadMsg rm=new ReadMsg();
rm.start();
} catch (Exception ex) {
ex.printStackTrace();
}
win.setTitle("聊天室客户端(已登录)");
}
}
public void actionPerformed(ActionEvent e){
String cmd=e.getActionCommand();
if(cmd.equals("登录")){
logon();
}
else if(cmd.equals("发送")){
String msg=tf.getText();
if(msg.length()>0){
sendMsg(nameInput.getText()+"说:" + msg);
tf.selectAll();
}
}else{
String msg=tf.getText();
if(msg.length()>0){
sendMsg(nameInput.getText()+"说:" + msg);
tf.selectAll();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -