Java Reference
In-Depth Information
package socketexample;
import java.io.*;
import java.net.*;
public class TCPServer {
public static void main(String args[]) {
// Listen to incoming connections at port 9000
try (ServerSocket serverSocket = new ServerSocket(9000)) {
String message = null;
while (!"STOP".equals(message)) {
// Accept incoming client
System.out.println("Waiting for connection...");
try ( // Set up socket for connection with client
Socket connectionSocket = serverSocket.accept();
// Set up input stream reader (from client)
DataInputStream incoming =
new DataInputStream(connectionSocket.getInputStream());
// Set up output stream writer (to client)
DataOutputStream outgoing =
new DataOutputStream(connectionSocket.getOutputStream());
) {
// Get the message the client sent
System.out.println("Waiting for message...");
message = incoming.readUTF().trim();
System.out.println("CLIENT SAID: " + message);
// Send message back
outgoing.writeUTF("MESSAGE RECEIVED\n");
if ("STOP".equals(message))
// Send additional line
outgoing.writeUTF("SERVER CLOSING DOWN\n");
// Close output stream to indicate that no more data is to be
sent
outgoing.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.
For the TCPClient class, the code reads as follows:
package socketexample;
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String args[]) {
Search WWH ::




Custom Search