📄 client.java
字号:
/**
*
*/
package com.tiankong;
/**
* @author Administrator
*
*/
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame{
private JTextField enter;
private JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;
String message="";
public Client(){
super("Client");
Container c=this.getContentPane();
enter=new JTextField();
enter.setEnabled(false);
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
sendData(e.getActionCommand());
}
});
c.add(enter,BorderLayout.NORTH);
display=new JTextArea();
c.add(new JScrollPane(display),BorderLayout.CENTER);
setSize(300,150);
setVisible(true);
}
public void runClient(){
Socket client;
try{
display.setText("Attempting connection\n");
client=new Socket(InetAddress.getByName("127.0.0.1"),5000);
display.append("Connection to: "+client.getInetAddress().getHostName());
output=new ObjectOutputStream(client.getOutputStream());
output.flush();
input=new ObjectInputStream(client.getInputStream());
display.append("\nGot I/O stream\n");
enter.setEnabled(true);
do{
try{
message=(String)input.readObject();
display.append("\n"+message);
display.setCaretPosition(display.getText().length());
}catch(ClassNotFoundException cnfex){
display.append("\nUnknow object type received");
}
}while(!message.equals("SERVER>>>TERMINATE"));
display.append("Closing connection.\n");
input.close();
output.close();
client.close();
}catch(EOFException eof){
System.out.println("Server terminated connection");
}catch(IOException e){
e.printStackTrace();
}
}
private void sendData(String s){
try{
message=s;
output.writeObject("CLIENT>>> "+s);
output.flush();
display.append("\nCLIENT>>>"+s);
}catch(IOException cnfex){
display.append("\nError writing object");
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Client app=new Client();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.runClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -