back | home |
Client Socket example |
---|
The client program establishes a connection to the server program on a particular host and port number in its listenSocket method, and sends the data entered by the end user to the server program in its actionPerformed method. The actionPerformed method also receives the data back from the server and prints it to the command line.
listenSocket Method public void listenSocket(){ //Create socket connection try{ socket = new Socket("kq6py.eng", 4321); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( socket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Unknown host: kq6py.eng"); System.exit(1); } catch (IOException e) { System.err.println("No I/O"); System.exit(1); } } actionPerformed Method The actionPerformed method is called by the Java platform for action events such as button clicks. This actionPerformed method code gets the text in the Textfield object and passes it to the PrintWriter object, which then sends it over the socket connection to the server program. The actionPerformed method then makes the Textfield object blank so it is ready for more end user input. Lastly, it receives the text sent back to it by the server and prints the text out. public void actionPerformed(ActionEvent event){ Object source = event.getSource(); if(source == button){ //Send data over socket String text = textField.getText(); out.println(text); textField.setText(new String("")); out.println(text); } //Receive text from server try{ String line = in.readLine(); System.out.println("Text received: " + line); } catch (IOException e){ System.err.println("Read failed"); System.exit(1); } } |
back | home |