[英]Java sockets with thread execution
i have coded a socket listener that should listen on port 80 and 81 and when data arrive on these ports execute operations on these data. 我编写了一个套接字侦听器,该侦听器应侦听端口80和81,并且当数据到达这些端口时,将对这些数据执行操作。 I want this listener to concurrently listen on both these ports and hav coded in the following way. 我希望该侦听器同时在这两个端口上侦听,并以以下方式进行编码。
import java.net.*;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class MultipleSocketServer implements Runnable {
private int a;
private ServerSocket connection;
private String TimeStamp;
private int ID;
public static void main(String[] args){
// System.out.print("ip");
// String gh="12345";
//System.out.println(gh.substring(1,3));
int port = 80;
int port1 = 81;
int count = 0;
double a=234.52121;
//System.out.println(bf3.toString());
try{
ServerSocket socket1 = new ServerSocket(port);
ServerSocket socket2=new ServerSocket(port1);
System.out.println("MultipleSocketServer Initialized");
Runnable runnable = new MultipleSocketServer(socket1, ++count);
Runnable run = new MultipleSocketServer(socket2, ++count);
Thread thread = new Thread(runnable);
Thread thread1 = new Thread(run);
while (true) {
//Socket connection = socket1.accept();
thread.start();
thread1.start();
}
}
catch (Exception e) {}
}
MultipleSocketServer(ServerSocket s, int i) {
this.connection = s;
this.ID = i;
}
public void run() {
while(true){
try {
Socket incoming=connection.accept();
BufferedInputStream is = new BufferedInputStream(incoming.getInputStream());
int character;
while((character = is.read())!=-1) {
.
.
do the input data handling here
.
.
}
}
catch(Exception e){}
}
}
}
But for some reason this does not seem to show the threaded/conncurrent behaviour. 但是由于某种原因,这似乎没有显示线程/并发行为。 I am testing this code using Hyperterminal, and every time i disconnect from hyperterminal, the program execution stops and "Socket is closed" exception is raised. 我正在使用超级终端测试此代码,并且每次我从超级终端断开连接时,程序执行都会停止,并且会引发“套接字已关闭”异常。
Any pointers would be of great help 任何指针都会有很大帮助
Cheers 干杯
You're starting threads in an endless loop. 您正在无休止的循环中启动线程。
while (true) {
//Socket connection = socket1.accept();
thread.start();
thread1.start();
}
I think though, that this is handled (ignored) in 但我认为,这是在
} catch (Exception e) {}
However, I suspect that the problem you describe is in in the handling code you didn't include. 但是,我怀疑您描述的问题在您未包含的处理代码中。 One pretty obvious idea: you don't call connection.close()
instead of incoming.close()
, do you? 一个很明显的主意:您不调用connection.close()
而不是来incoming.close()
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.