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

时间:2011-11-18 20:40:54

标签: java multithreading sockets networking

我遇到了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");
}

1 个答案:

答案 0 :(得分:3)

你正在ClientServerThread构造函数中执行“accept”,它会阻塞,直到TCP连接进入。在构造函数完成之前,你永远不会进入线程启动。