Advertisement
metalni

TCP CLIENT

Jan 23rd, 2022
966
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.*;
  2. import java.net.Socket;
  3. import java.net.UnknownHostException;
  4. import java.util.Scanner;
  5.  
  6. public class TCPClient extends Thread{
  7.  
  8.     private String serverName;
  9.     private int serverPort;
  10.  
  11.     public TCPClient(String serverName, int serverPort) {
  12.         this.serverName = serverName;
  13.         this.serverPort = serverPort;
  14.     }
  15.  
  16.     @Override
  17.     public void run() {
  18.         Socket socket = null;
  19.  
  20.         Scanner scanner = null;
  21.         PrintWriter writer = null;
  22.         BufferedReader reader = null;
  23.  
  24.         try {
  25.             socket = new Socket(serverName, serverPort);
  26.             writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
  27.             reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  28.             scanner = new Scanner(System.in);
  29.             while (true) {
  30.                 String receivedMessage = reader.readLine();
  31.                 System.out.println(receivedMessage);
  32.                 String line = scanner.nextLine();
  33.                 writer.println(line);
  34.                 writer.flush();
  35.             }
  36.         } catch (UnknownHostException e) {
  37.             e.printStackTrace();
  38.         } catch (IOException e) {
  39.             e.printStackTrace();
  40.         }
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         TCPClient client = new TCPClient("localhost",8888);
  45.         client.start();
  46.     }
  47. }
  48.  
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement