【发布时间】:2014-01-27 04:41:00
【问题描述】:
我需要帮助我正在尝试制作用于在 java 中复制文件的客户端服务器应用程序...我有 MainWnd 对象,它创建 TCPServer 对象,在发送按钮上它将创建 TCPClient 对象,该对象将初始数据发送到对手 TCPServer并将打开给定数量的监听线程(让它成为n)(这个监听线程在这里只是因为它们接受一个文件)(每个线程在不同的端口上监听发送回TCPClient)TCPClient然后创建n 发送文件的其他 TCPClients 线程...我已经得到它并且它正在运行。问题是,当他点击按钮中断时,文件接收可能会被接收者中断。我无法获取接收方 TCPServer 线程中断的信息,这应该会杀死正在下载文件的 n 个线程。
我认为问题出在 TCPServer,在哪里是无限循环,但是其中的 Socket 会导致循环阻塞,所以我无法进入 Connection 类并杀死这 n 个线程。
TCP 服务器
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());}
}
连接
while (true)
{
byteRead = input.read();
//Thread.sleep(100);
if(interruptedSending) {
TCPClient tcpClient = new TCPClient(clientSocket.getPort(), clientSocket.getInetAddress().getHostAddress());
tcpClient.sendInterruptedData();
interruptedSending = false;
}
char lowChar;
if(byteRead == -1) {
break;
} else
lowChar = (char)byteRead;
lowData += lowChar;
if(lowData.length() >= 2) {
if (lowData.substring(lowData.length()-2).compareTo("//") == 0) {
break;
} else if (lowData.length() > 6) {
byteData.add((byte)byteRead);
}
}
}
在连接中有更多的行,但它们主要只是解析一个协议。 非常感谢您的帮助。我希望我写得干净...
【问题讨论】:
标签: java multithreading sockets