back | home |
Server Socket example |
---|
The server program establishes a socket connection on Port 4321 in its listenSocket method. It reads data sent to it and sends that same data back to the server in its actionPerformed method. listenSocket Method The listenSocket method creates a ServerSocket object with the port number on which the server program is going to listen for client communications. The port number must be an available port, which means the number cannot be reserved or already in use. For example, Unix systems reserve ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use. public void listenSocket(){ try{ server = new ServerSocket(4321); } catch (IOException e) { System.out.println("Could not listen on port 4321"); System.exit(-1); } Next, the listenSocket method creates a Socket connection for the requesting client. This code executes when a client starts up and requests the connection on the host and port where this server program is running. When the connection is successfully established, the server.accept method returns a new Socket object. try{ client = server.accept(); } catch (IOException e) { System.out.println("Accept failed: 4321"); System.exit(-1); } Then, the listenSocket method creates a BufferedReader object to read the data sent over the socket connection from the client program. It also creates a PrintWriter object to send the data received from the client back to the server. try{ in = new BufferedReader(new InputStreamReader( client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch (IOException e) { System.out.println("Read failed"); System.exit(-1); } } Lastly, the listenSocket method loops on the input stream to read data as it comes in from the client and writes to the output stream to send the data back. while(true){ try{ line = in.readLine(); //Send data back to client out.println(line); } catch (IOException e) { System.out.println("Read failed"); System.exit(-1); } }
actionPerformed Method
The actionPerformed method is called by the Java platform for action events such as button clicks.
This actionPerformed method uses the text stored in the line object to initialize the textArea object so
the retrieved text can be displayed to the end user.
public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == button){ textArea.setText(line); } } |
back | home |