java.net 操练__教程 |
|
日期:2007-5-20 1:27:33 人气:164 [大 中 小] |
|
|
|
infBox.append("\nGet Streams...");
}
/** * */ private void waitForConnection() throws IOException { infBox.append("wait for a Client..."); serverSocket=server.accept(); infBox.append("connected by"+serverSocket.getInetAddress().getHostName());
}
public static void main(String[] args) { server my=new server(); my.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); my.runServer(); } }
客户端
/* * Created on 2005-3-18 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package netChat; import javax.swing.*;
import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*;
/** * @author AppleTian * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class client extends JFrame {
private JTextField messageBox; private JTextArea infBox; private ObjectInputStream input; private ObjectOutputStream output; private String mg=""; private String chatServer; private Socket client; public client(String host){ super("client...."); chatServer=host; Container c=getContentPane();
messageBox=new JTextField(); messageBox.setEnabled(false); messageBox.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ sendData(e.getActionCommand()); }
}); c.add(messageBox,BorderLayout.NORTH); infBox=new JTextArea(); c.add(infBox,BorderLayout.CENTER);
setSize(500,400); setVisible(true);
}
/** * @param actionCommand */ protected void sendData(String actionCommand) { try{ mg=messageBox.getText(); output.writeObject(mg); output.flush(); infBox.append("\nsend to server: "+mg); }catch(IOException e){ infBox.append("\nIOException in sendData.."); }
} public void runClient(){ try{
connectToServer(); getStreams(); processConnection(); closeConnection(); }catch(IOException e){ infBox.append(e.toString()); }
}
/** * */ private void closeConnection()throws IOException { // TODO Auto-generated method stub infBox.append("\nclose..."); output.close(); input.close(); client.close();
}
/** * */ private void processConnection() throws IOException{ // TODO Auto-generated method stub messageBox.setEnabled(true ); do{ try{ mg=(String )input.readObject(); infBox.append("\nFrom server: "+mg); infBox.setCaretPosition(infBox.getText().length()); }catch(ClassNotFoundException e){ infBox.append("classNotFound...\n"); } }while(mg!="end"); |
|
出处:本站原创 作者:佚名 |
|
|