?? server.java
字號:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame {
private JTextField tf;
private JTextArea display;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;
public Server(){
super( "Server" );
Container container = getContentPane();
tf = new JTextField();
tf.setEnabled( false );
tf.addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent event )
{
sendData( event.getActionCommand() );
}
}); // end call to addActionListener
container.add( tf, BorderLayout.NORTH );
display = new JTextArea();
container.add( new JScrollPane( display ),
BorderLayout.CENTER );
setSize( 300, 150 );
setVisible( true );
}
public void runServer(){
try {
server = new ServerSocket( 5000, 100 );
while ( true ) {
waitForConnection();
getStreams();
processConnection();
closeConnection();
++counter;
}
}
catch ( EOFException eofException ) {
System.out.println( "Client terminated connection" );
}
catch ( IOException ioException ) {
ioException.printStackTrace();
}
}
private void waitForConnection() throws IOException{
display.setText( "Waiting for connection\n" );
connection = server.accept();
display.append( "Connection " + counter +" received from: " +connection.getInetAddress().getHostName() );
}
private void getStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream() );
output.flush();
input = new ObjectInputStream(connection.getInputStream() );
display.append( "\nGot I/O streams\n" );
}
private void processConnection() throws IOException{
String message = "SERVER>>> Connection successful";
output.writeObject( message );
output.flush();
tf.setEnabled( true );
do {
try {
message = ( String ) input.readObject();
display.append( "\n" + message );
display.setCaretPosition(display.getText().length() );
}
catch ( ClassNotFoundException classNotFoundException ) {
display.append( "\nUnknown object type received" );
}
}
while ( !message.equals( "CLIENT>>> TERMINATE" ) );
}
private void closeConnection() throws IOException{
display.append( "\nUser terminated connection" );
tf.setEnabled( false );
output.close();
input.close();
connection.close();
}
private void sendData( String message ){
try {
output.writeObject( "SERVER>>> " + message );
output.flush();
display.append( "\nSERVER>>>" + message );
}
catch ( IOException ioException ) {
display.append( "\nError writing object" );
}
}
public static void main( String args[] ){
Server application = new Server();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
application.runServer();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -