Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedInputStream;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.Scanner;
- public class prog01RelayTCP {
- public static void main(String[] argv) throws Exception {
- final int NUM_BYTES = 80;
- String servip = "147.97.156.237";
- int servport = 11234;
- int clientport = 1234;
- if (argv.length >= 4)
- {
- try {
- // Read server port
- servport = Integer.parseInt(argv[0]);
- } catch (NumberFormatException e) {
- System.err.println("First argument must be an integer");
- System.exit(1);
- }
- // Read server IP address
- servip = argv[1];
- try {
- // Read relay port
- clientport = Integer.parseInt(argv[2]);
- } catch (NumberFormatException e) {
- System.err.println("Third argument must be an integer");
- System.exit(1);
- }
- try {
- // Read relay port
- int tmp = Integer.parseInt(argv[3]);
- // Change if argv[2] was actually the server port
- if( tmp != servport && clientport == servport )
- clientport = tmp;
- } catch (NumberFormatException e) {
- System.err.println("Fourth argument must be an integer");
- System.exit(1);
- }
- }
- servip = "localhost";
- servport = 11234;
- clientport = 1234;
- ServerSocket clientSS = null;
- byte[] buf = new byte[NUM_BYTES];
- try {
- // Open socket for client
- clientSS = new ServerSocket(clientport);
- while (true) {
- // Connect to server
- Socket serverSocket = new Socket(servip, servport);
- // Initialize server I/O
- Scanner servIn = new Scanner(serverSocket.getInputStream());
- PrintWriter servOut = new PrintWriter(serverSocket.getOutputStream(), true);
- // Connect to client
- try (Socket clientSocket = clientSS.accept()) {
- System.out.println("Connected to Client");
- // Initialize client I/O
- BufferedInputStream clientIn = new BufferedInputStream(clientSocket.getInputStream());
- PrintWriter clientOut = new PrintWriter(clientSocket.getOutputStream(), true);
- // Read input from client
- int nRead = clientIn.read(buf, 0, NUM_BYTES);
- // If the socket was closed, try again
- if (nRead <= 0) {
- // Close sockets
- clientIn.close();
- clientSocket.close();
- // Serve next one
- continue;
- }
- // Relay client data to server
- servOut.print(new String(buf));
- servOut.flush();
- System.out.println("CLIENT: " + new String(buf));
- // Relay server data to client
- String serverInput = servIn.nextLine();
- System.out.println("SERVER: " + serverInput);
- clientOut.println(serverInput);
- }
- serverSocket.close();
- }
- } catch (IOException ioEx) {
- System.out.println("Exception");
- } finally {
- clientSS.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement