在java中连续地通过套接字传输数据

moi*_*fse 6 java sockets bufferedreader

我想通过推送和拉动异步发送/接收从一个端点到另一个端点(peer2peer)的连续数据流

因此,为了首先解决通信,我开始使用jax-ws soap绑定webservice,因为它有一个端点和推送机制的ws-addressing,但它似乎是很多开销(根据文档很重,因为不熟悉ws-*,我没有实现它,因为我需要多个客户端稍后监听流,并且流是24/7我想要线程可管理的套接字).

然后我拿了jax-rs但它不包含ws-addressing.(jax-rs 2.0)我也查看了websockets但它需要一个app服务器但是我想要一个jvm可支持的代码

所以,现在我正在尝试使用基本套接字,但我遇到的问题是通过服务器上的套接字流式传输数据,客户端不断接收它.这是第一次阅读,但没有进一步.其次,我怎样才能使它异步?

public class sSocket {  
public static void main(String args[]) throws IOException{  
    int i = 15000;
    ServerSocket ss;
    Socket socket = null;
    ss = new ServerSocket(i);        
    try
    {
        socket = ss.accept();
        socket.setKeepAlive(true);          

           int iii = 0;            
               System.out.println("New connection accepted " +  socket.getInetAddress() + ":" + socket.getPort());   
               BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
               BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

           while(iii<9)
           {
               Thread.sleep(2000);
               output.write("good" + iii + "\n");
               //System.out.print(input.readLine().toString());
               output.flush();
               iii++;
           }
               //socket.close();
       }        

    catch(IOException e)
    {
        e.printStackTrace();
    }   
}
}

public class cSocket {  
public static void main(String args[]) throws InterruptedException, IOException{
    Socket client = new Socket("127.0.0.1", 15000);     
try{
    client.setKeepAlive(true);
    DataOutputStream out = new DataOutputStream(client.getOutputStream());
    out.writeBytes("Hi Server! I'm " + client.getLocalSocketAddress() + "\n" );     
     BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
     String s;       
     while(true){
     if((s = input.readLine()) != null)
    {
        System.out.println("Message from Server: " + s);
    }}
     //client.close();
    }
    catch(Exception e){
    e.printStackTrace();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

[toString()不可用 - 没有挂起的线程]我看到这停止了eclipse中的代码.问题似乎基本上是在客户端的input.readLine()根源:错误是连接重置:我假设是因为readLine()已达到"EOF"

use*_*421 0

不要继续创建新的流。在插座的使用寿命内,两端均使用相同的产品。您正在丢失缓冲区中的数据。

你不需要一直调用setKeepalive()。一次就够了。