Rags
Rags

Reputation: 434

Socket programming using threads in Java

I am having difficulty with Java threads. In this program I want it to read TCP and UDP simultaneously, but in my code only when a TCP request has been sent the code will proceed to UDP.

I want them to work simultaneously, can anyone help me?

Here's what I have so far:

public class Newthreads {
  ServerSocket socket;
  DatagramSocket udpSocket;
  private int id=1;

  public Newthreads() throws IOException {
    socket=new ServerSocket(9000);
    udpSocket=new DatagramSocket(5000);
    System.out.println("listening on 7000");
    System.out.println("udp listening at 5000");
    ClientServerThread clientThread=new ClientServerThread(socket);``
    clientThread.start();
    SlientServerThread e =new SlientServerThread(udpSocket);
    e.start();
  }

  public static void main(String[] args) throws IOException {
    new Newthreads();
  }
}

class ClientServerThread extends Thread {
  Socket clientSocket;
  int child;
  public ClientServerThread(ServerSocket conn) throws IOException {
    //To change body of created methods use File | Settings | File Templates.
    System.out.println("i m here");
    clientSocket=conn.accept();
  }
  public void run() {
    System.out.println("executing TCP");
  }
}

class SlientServerThread extends Thread {
  Socket conn;
  DatagramPacket recvPacket;
  private byte[] recvdata=new byte[10];

  SlientServerThread(DatagramSocket tcpSocket) throws IOException {
  recvPacket=new DatagramPacket(recvdata,recvdata.length);
  tcpSocket.receive(recvPacket);
  System.out.println("hey thread 2");
}

Upvotes: 0

Views: 2444

Answers (1)

ribram
ribram

Reputation: 2460

You are doing the "accept" in the ClientServerThread constructor which is blocking until a TCP connection comes in. You are never getting to the thread start until the constructor completes.

Upvotes: 3

Related Questions