📄 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();
enterField=new JTextField();
enterField.setEnabled(false);
enterField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event)
{
sendData(event.getActionCommand());
enterField.setText("");
}
});
container.add(enterField,BorderLayout.NORTH);
displayArea=new JTextArea();
container.add(new JScrollPane(displayArea),BorderLayout.CENTER);
setSize(450,200);
setVisible(true);
}
public void runClinet()
{
try{
connectToServer();
getStreams();
processConnection();
closeConnection();
}
catch(EOFException eofException){
System.out.println("Server terminated connection");
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
private void getStreams()throws IOException
{
output=new ObjectOutputStream(
client.getOutputStream());
output.flush();
input=new ObjectInputStream(
client.getInputStream());
displayArea.append("\nGot I/O stream\n");
}
private void connectToServer()throws IOException
{
displayArea.setText("Attempting connection\n");
client=new Socket(
InetAddress.getByName(chatServer),5000);
displayArea.append("Connected to:"+client.getInetAddress().getHostName());
}
private void processConnection()throws IOException
{
enterField.setEnabled(true);
do{
try{
message=(String)input.readObject();
displayArea.append("\n"+message);
displayArea.setCaretPosition(
displayArea.getText().length());
}
catch(ClassNotFoundException classNotFoundException){
displayArea.append("\nUnkown object type received");
}
}while(!message.equals("SERVER>>> TERMINATE"));
}
private void closeConnection()throws IOException
{
displayArea.append("\n Closing connection");
output.close();
input.close();
client.close();
}
private void sendData(String message)
{
try{
output.writeObject("CLIENT>>>"+message);
output.flush();
displayArea.append("\nCLIENT>>>"+message);
}
catch(IOException ioException){
displayArea.append("\nError writing object");
}
}
public static void main(String args[])
{
Client application;
if(args.length==0)
application=new Client("172.17.49.221");
else
application=new Client(args[0]);
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.runClinet();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -