简体   繁体   中英

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");
}

您正在ClientServerThread构造函数中执行“接受”操作,该操作在TCP连接进入之前一直处于阻塞状态。在构造函数完成之前,您永远不会进入线程启动。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM