Java中使用线程的套接字编程

Java中使用线程的套接字编程,java,multithreading,sockets,networking,Java,Multithreading,Sockets,Networking,我在Java线程方面有困难。在这个程序中,我希望它能够同时读取TCP和UDP,但在我的代码中,只有当TCP请求被发送时,代码才会转到UDP 我想让他们同时工作,有人能帮我吗 以下是我目前掌握的情况: public class Newthreads { ServerSocket socket; DatagramSocket udpSocket; private int id=1; public Newthreads() throws IOException { socke

我在Java线程方面有困难。在这个程序中,我希望它能够同时读取TCP和UDP,但在我的代码中,只有当TCP请求被发送时,代码才会转到UDP

我想让他们同时工作,有人能帮我吗

以下是我目前掌握的情况:

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构造函数中执行“accept”,该构造函数在TCP连接进入之前一直处于阻塞状态。在构造函数完成之前,您永远无法启动线程。

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

看看这个:看看这个: