[英]Socket programming using threads in Java
我在使用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构造函数中执行“接受”操作,该操作在TCP连接进入之前一直处于阻塞状态。在构造函数完成之前,您永远不会进入线程启动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.