【问题标题】:Connection between Nodejs and Java. When client of java connect to nodejs server then it shows me error,Nodejs 和 Java 之间的连接。当 java 的客户端连接到 nodejs 服务器时,它会显示错误,
【发布时间】:2016-05-08 12:30:43
【问题描述】:

我在 node.js 上有一个服务器,在 Java 上有一个客户端。当 Java 客户端连接到 Nodejs 服务器时,它会显示如下错误。

我在 node.js 上有一个服务器

const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello from server\r\n');
c.pipe(c);
});

server.on('data', ()=>{
Console.log(data); 
});
server.on('error', (err) => {
throw err;
});
server.listen(6969, () => {
console.log('server bound');
});

我有一个 java 代码。

public class NodeJsEcho { 
// socket object
private Socket socket = null; 
public static void main(String[] args) throws UnknownHostException,    
IOException, ClassNotFoundException { 
    // class instance 
    NodeJsEcho client = new NodeJsEcho(); 
    // socket tcp connection 
    String ip = "127.0.0.1"; 
    int port = 6969; 
    client.socketConnect(ip, port); 
    // writes and receives the message

    String message = "message123"; 
    System.out.println("Sending: " + message); 
    String returnStr = client.echo(message); 
    System.out.println("Receiving: " + returnStr); 
    } 
// make the connection with the socket 
private void socketConnect(String ip, int port) throws UnknownHostException,    
 IOException{
    System.out.println("[Connecting to socket...]"); 
    this.socket = new Socket(ip, port); 
    }
// writes and receives the full message int the socket (String) 
public String echo(String message) 
{
    try {
        // out & in 
        PrintWriter out = new PrintWriter(getSocket().getOutputStream(),    
        true); 
        BufferedReader in = new BufferedReader(new   
        InputStreamReader(getSocket().getInputStream()));
        // writes str in the socket and read 
        out.println(message); 
        String returnStr = in .readLine();
        return returnStr; 
        } catch (IOException e) 
    {
            e.printStackTrace();
            }
    return null; 
    } // get the socket instance 
private Socket getSocket() 
{
    return socket; 
    }

}

它向我显示了以下服务器端的错误:

 client connected
  events.js:141
  throw er; // Unhandled 'error' event
  ^

Error: read ECONNRESET
at exports._errnoException (util.js:870:11)
at TCP.onread (net.js:550:26)
Done.

【问题讨论】:

  • 您在客户端看到任何错误吗?它有连接吗?
  • 客户端没有错误。
  • 客户端是:[Connecting to socket...] 发送:message123 接收:来自服务器的hello
  • 是的,它在客户端输出..

标签: java node.js socket.io


【解决方案1】:

您没有关闭客户端的套接字 - 导致连接重置。

// In echo()
in.close();
out.close();

// In main()
getSocket().close();

【讨论】:

  • @QandeelHaider - 尝试关闭流。
猜你喜欢
  • 1970-01-01
  • 2017-12-29
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多