网络连接问题
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 = this.getContentPane();
enterField = new JTextField();
enterField.setEditable(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);
this.setSize(300,150);
this.setVisible(true);
}//end client constructor
private void runClient()
{
try {
connectToServer();
getStreams();
processConnection();
} catch (Exception ex) {
System.err.println("client terminated connection");
}
finally{
closeConnection();
}
}//end runclient
private void connectToServer()throws IOException
{
displayMessage("Attempting connection\n");
client =new Socket(InetAddress.getByName(chatServer),12345);
displayMessage("Connected to:"+client.getInetAddress().getHostName());
}
private void getStreams()throws IOException
{
output = new ObjectOutputStream(client.getOutputStream());
output.flush();
input =new ObjectInputStream(client.getInputStream());
displayMessage("\nGot I/O streams\n");
}
private void processConnection()throws IOException
{
setTextFieldEditable(true);
do{
try {
message = (String) input.readObject();
displayMessage("\n" + message);
} catch (ClassNotFoundException ex) {
displayMessage("\nUnknown object type received");
} catch (IOException ex) {
}
}while (!message.equals("SERVER>>>TERMINATE"));
}//end proceccConnection
private void closeConnection()
{
try {
output.close();
input.close();
client.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void sendData(String message)
{
try {
output.writeObject("CLIENT>>>" + message);
output.flush();
displayMessage("\nCLIENT>>>" + message);
} catch (IOException ex) {
displayArea.append("\nError writing object");
}
}
private void displayMessage(final String messageToDisplay)
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
displayArea.append(messageToDisplay);
displayArea.setCaretPosition(displayArea.getText().length());
}
}
);
}
private void setTextFieldEditable(final boolean editable)
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
enterField.setEditable(editable);
}
}
);
}
public static void main(String args[])
{
Client application;
application=new Client("192.168.0.7");
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.runClient();
}
}
这是客户端代码