2011-11-18 34 views
0

我对Java线程有困难。在这个程序中,我希望它同时读取TCP和UDP,但是在我的代码中,只有当发送TCP请求时,代码才会进入UDP。使用Java中的线程进行套接字编程

我希望他们同时工作,任何人都可以帮助我吗?

这是我到目前为止有:

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

看看这个:http://codetoearn.blogspot.com/2013/01/multi-thread-tcp-socket-programming.html – ehsun7b

回答

3

你正在做的“接受”,在ClientServerThread构造函数阻塞,直到TCP连接进来时你永远不会得到该线程开始到构造函数。完成。