java在使用带套接字的循环时进入另一个线程
我需要一个帮助,我正试图使客户端服务器应用程序复制文件在java。。。我有一个MainWnd对象,它创建了TCPServer对象,在send按钮上,它将创建TCPClient对象,该对象将初始数据发送给对手的TCPServer,并将打开给定数量的侦听线程(设为n)(这个侦听线程在这里仅仅是因为它们接受一个文件)(每个线程在不同的端口上侦听,并将其发送回TCPClient)TCPClient然后创建n个其他TCPClient线程,用于发送文件。。。我有这个,它正在运行。问题是,当接收者点击“中断”按钮时,文件接收可能会被中断。我无法获取接收器的TCPServer线程的中断信息,这将杀死正在下载文件的这n个线程 我认为问题出在TCPServer中,其中是无限循环,但其中的套接字将导致循环阻塞,因此我无法进入连接类并杀死这n个线程 TCP服务器java在使用带套接字的循环时进入另一个线程,java,multithreading,sockets,Java,Multithreading,Sockets,我需要一个帮助,我正试图使客户端服务器应用程序复制文件在java。。。我有一个MainWnd对象,它创建了TCPServer对象,在send按钮上,它将创建TCPClient对象,该对象将初始数据发送给对手的TCPServer,并将打开给定数量的侦听线程(设为n)(这个侦听线程在这里仅仅是因为它们接受一个文件)(每个线程在不同的端口上侦听,并将其发送回TCPClient)TCPClient然后创建n个其他TCPClient线程,用于发送文件。。。我有这个,它正在运行。问题是,当接收者点击“中断”
public void setSendInterruption() {
this.interruptedSending = true;
//c.setSendInterruption();
}
public TCPServer(int port, int socketNums, Map<Byte, LinkedList<Byte>> realData, File file, int fileLength) {
this.serverPort = port;
this.socketNums = socketNums;
if(file != null)
this.file = file;
if(fileLength != -1)
this.fileLength = fileLength;
if(realData != null)
this.realData = realData;
if(tmpData != null)
this.tmpData = tmpData;
}
@Override
public void run() {
try {
System.out.println(this.getId());
listenSocket = new ServerSocket(serverPort);
System.out.println("server start listening... ... ...");
while(true) {
if(interruptedSending)
System.out.println("Here I never come");
Socket clientSocket = listenSocket.accept();
Connection c = new Connection(clientSocket, socketNums, realData, file, fileLength);
}
}
catch(IOException e) {
System.out.println("Listen :"+e.getMessage());}
}
在连接中有更多的行,但它们主要是解析协议。
非常感谢你的帮助。我希望我写的很干净…据我所知,每个连接都有一个运行它的线程。您想中断这些线程中的每一个,但无法从线程内部中断,因为它们卡在input.read()中 如果这就是你的意思,就这么做: 在连接的构造函数中保存线程,以便以后可以访问它。 创建killThread()-方法或类似方法,以便可以从外部访问线程:
public void killThread() {
thread.interrupt(); //thread is the thread you saved in the constructor
}
如果要终止连接线程,请调用killThread()。这将导致线程抛出java.lang.InterruptedException,不管它现在在哪里。
您可以忽略这一点(因为您希望线程无论如何都会死掉),也可以使用
try {
//your loop
} catch (InterruptedException e) {
return;
}
这将很好地结束线程,而不会抛出异常
try {
//your loop
} catch (InterruptedException e) {
return;
}