我正在尝试让两个或更多线程通过java套接字将输出流写入服务器端应用程序同时。
但他们正按顺序写作。
这个MVCE行为相同..
SERVER LISTENER
public static void main(String[] args) {
Socket socket=null;
try{
ServerSocket serverSocket = new ServerSocket(5050);
while (true) {
logger.warn("listening");
socket = serverSocket.accept();
new TestingSession(socket).start();
}
} catch(Exception e) {}
}
SERVER THREAD:
class TestingSession extends Thread {
private static final Logger logger = Logger.getLogger(Class.class.getName());
private Socket socket;
TestingSession(Socket socket) {
try {
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
this.socket = socket;
while (!socket.isClosed()) {
System.out.println(dataInputStream.readUTF());
}
} catch (Exception e) {
}
}
}
客户主要
public class Run {
public static void main(String[] args) {
UpdateTest t1 = new UpdateTest();
UpdateTest t2 = new UpdateTest();
t1.start();
t2.start();
System.out.println("finished creation");
}
}
客户端线程
public class UpdateTest extends Thread {
public void run() {
try {
Socket socket;
socket = new Socket("127.0.0.1", 5050);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
for(int i=0; i <100;i++){
Thread.sleep(50);
dataOutputStream.writeUTF(""+i);
System.out.println(i);
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}}
客户的输出:
完成创作
1 1 2 2 3 3 4 4 5 5
服务器输出:
1 2 3 4 5 6 ... 97 99 100
- 异常套接字关闭.--
倾听
1 2 3 4 5 6 .. 99 100
答案 0 :(得分:3)
我想你可能搞砸了课程定义。我的IDE告诉我socket
中的实例变量TestingSession
未被使用。然后我注意到你在构造函数中编写了整个服务器“thread”,导致start()
什么都不做,并使你的服务器只在一个线程中执行。
改变这个:
class TestingSession extends Thread {
private static final Logger logger = Logger.getLogger(Class.class.getName());
private Socket socket;
TestingSession( Socket socket ) {
try {
DataInputStream dataInputStream = new DataInputStream( socket.getInputStream() );
this.socket = socket;
while( !socket.isClosed() ) {
System.out.println( dataInputStream.readUTF() );
}
} catch( Exception e ) {
}
}
}
对此:
class TestingSession extends Thread {
private static final Logger logger = Logger.getLogger(Class.class.getName());
private Socket socket;
TestingSession( Socket socket ) {
this.socket = socket;
}
@Override
public void run() {
try {
DataInputStream dataInputStream = new DataInputStream( socket.getInputStream() );
while( !socket.isClosed() ) {
System.out.println( dataInputStream.readUTF() );
}
} catch( Exception e ) {
}
}
}