Socket connection and thread

In this chapter you will learn:

  1. How to do socket communication within thread

Socket and thread

The following code shows how to do Socket commnunication within a thread.

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
/*from  j  av  a  2 s. co m*/
public class Main extends Thread {
  public void run() {
    try {
      Socket socket = new Socket("127.0.0.1", 2000);

      DataInputStream in = new DataInputStream(socket.getInputStream());
      BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());

      while (true) {
        System.out.print("Enter response: ");
        String response = console.readLine();
        out.writeUTF(response);

        String message = in.readUTF();
        System.out.println(message);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    Thread t = new Main();
    t.start();
  }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use ServerSocket to create a server
  2. Local Port Scanner
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies