📄 chatclient.java
字号:
package ChatClient;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Container;
import java.net.*;
import java.io.*;
public class ChatClient extends JFrame implements Runnable,ActionListener
{
JTextArea txtDisplay;
JTextArea txtSMsg;
JButton clear;
JButton send;
DataInputStream m_in=null;
DataOutputStream m_out=null;
public ChatClient()
{
//super();
setResizable(false);
setTitle("Java聊天室-客户端");
getContentPane().setLayout(null);
setBounds(100, 100, 400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txtDisplay = new JTextArea();
txtDisplay.setBounds(20, 20, 350, 200);
getContentPane().add(txtDisplay);
txtSMsg = new JTextArea();
txtSMsg.setBounds(20,240,350,80);
getContentPane().add(txtSMsg);
clear = new JButton();
clear.setText("清屏");
clear.setBounds(20, 340, 77, 25);
getContentPane().add(clear);
clear.addActionListener(this);
send = new JButton();
send.setText("发送");
send.setBounds(290,340,77,25);
getContentPane().add(send);
send.addActionListener(this);
setVisible(true);
try{
//获取applet 的URL ,即聊天服务者地址
//URL url=getLocale() ;
//获取服务器IP地址
//InetAddress inetaddr=InetAddress.getByName(url.getHost());
Socket m_socket;
//屏幕显示服务器IP地址、通信协议
//System.out.println("Server:"+inetaddr+" "+url.getHost()+" "+url.getProtocol());
//创建与服务器IP地址连接的套接口,5555是聊天服务者套接口端口
m_socket=new Socket("localhost",5555);
//在套接口上建立输入流
m_in=new DataInputStream(m_socket.getInputStream());
//在套接口上建立输出流
m_out=new DataOutputStream(m_socket.getOutputStream());
}
catch (Exception e)
{
System.out.println("Error:"+e);
}
new Thread(this).start();
}
public void actionPerformed(ActionEvent event)
{
String b=txtSMsg.getText();
if(event.getSource()==send)
{
txtSMsg.setText("");
//将聊天者输入的消息发送给 ChatServer
try
{
m_out.writeUTF(b); //向聊天服务者发送一UTF格式字符串。
}
catch(IOException e){}
}
else if(event.getSource()==clear)
txtDisplay.setText("");
}
public void run()
{
try
{
while(true)
{
//聊天者监听对应服务线程发来的消息,它将封锁在该语句中,
//直到消息到来。
String s=m_in.readUTF(); //读一个UTF格式字符串。
if(s!=null)
//将消息显示在信息显示窗口中。
txtDisplay.append(s+"\n");
}
}
catch(Exception e)
{
txtDisplay.append("Network problem or Server down.\n");
}
}
public void stop()
{
try
{
m_out.writeUTF("leave");
}
catch(IOException e){}
}
public static void main(String[] args)
{
ChatClient ss = new ChatClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -