📄 client.java
字号:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String chatServer;
private Socket client;
// 客户端构造函数
public Client( String host )
{
super( "客户端Client" );
// 指定客户端连接的主机地址
chatServer = host;
Container container = getContentPane();
// 消息显示区
displayArea = new JTextArea();
container.add( new JScrollPane( displayArea ),
BorderLayout.CENTER );
// 建立一个单文本行发送消息给主机
enterField = new JTextField();
enterField.setEnabled( false );
// 注册回车发送消息事件
enterField.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event )
{
sendData( event.getActionCommand() );
}
} );
container.add( enterField, BorderLayout.SOUTH );
setSize( 400, 300 );
setVisible( true );
}
// 连接到服务端并接受服务端的消息
public void runClient()
{
try {
//建立一个到服务端的连接
displayArea.setText( "正在连接服务端......\n" );
client = new Socket(
InetAddress.getByName( chatServer ), 5000 );
displayArea.append( "连接到主机: " +
client.getInetAddress().getHostName() );
// 获得输入输出流
output = new ObjectOutputStream(
client.getOutputStream() );
output.flush();
input = new ObjectInputStream(
client.getInputStream() );
displayArea.append( "\n获得输入输出流\n" );
// 接受消息并显示在displayArea
// 使发送消息区能编辑
enterField.setEnabled( true );
do {
// 读取服务端的消息并在消息显示区显示
try {
message = ( String ) input.readObject();
displayArea.append( "\n" + message );
displayArea.setCaretPosition(
displayArea.getText().length() );
}
// 捕获异常
catch ( ClassNotFoundException classNotFoundException ) {
displayArea.append( "\nUnknown object type received" );
}
} while ( !message.equals( "服务端:离线" ) );
// 关闭连接
displayArea.append( "\n关闭连接" );
output.close();
input.close();
client.close();
}
catch ( EOFException eofException ) {
System.out.println( "服务器关闭了连接" );
}
catch ( IOException ioException ) {
ioException.printStackTrace();
}
}
// 发送消息到服务端
private void sendData( String message )
{
try {
output.writeObject( "客户端说:" + message );
output.flush();
displayArea.append( "\n客户端说:" + message );
}
catch ( IOException ioException ) {
displayArea.append( "\nError writing object" );
}
}
// 主函数
public static void main( String args[] )
{
Client application;
if ( args.length == 0 )
application = new Client( "127.0.0.1" );
else
application = new Client( args[ 0 ] );
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
application.runClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -