通过socket连接node.js和java
我正在尝试从 Java 客户端连接到我的服务器(使用 sockets.io
运行 nodejs
)。我希望它能够检测客户端何时到达服务器并将某些内容打印到控制台。
连接成功后,第二步是客户端能够通过套接字向服务器发送字符串。
我运行 JAVA 代码,但服务器没有检测到客户端连接,我不明白为什么会发生这种情况,而且我找不到与 Nodejs 进行套接字通信的良好资源。
服务器端代码:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(65432, () => {
console.log('listening on *:65432');
});
app.get('/', function(req, res) {
res.send('connection successfull');
});
io.on('connection', function(socket) {
socket.on('send coordinates', function(data){
console.log('a user connected');
});
});
console.log('listening to port');
客户端代码:
public static void main(String[] args) {
Socket socket = null;
OutputStreamWriter osw;
String str = "Hello World";
try {
socket = new Socket(**[serverIP]**, 65432);
osw =new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
osw.write(str, 0, str.length());
} catch (IOException e) {
System.err.print(e);
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to connect to my server (which runs nodejs
with sockets.io
) from my Java client. I want it to detect whenever the client reaches the server and print something to the console.
After the connection is successful, 2nd step would be to the client to be able to send a string to the server via sockets.
I run the JAVA code but the server is not detecting the client connection and I don't understand why is that happening and I can't find good resources for sockets communication with nodejs.
server-side code:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(65432, () => {
console.log('listening on *:65432');
});
app.get('/', function(req, res) {
res.send('connection successfull');
});
io.on('connection', function(socket) {
socket.on('send coordinates', function(data){
console.log('a user connected');
});
});
console.log('listening to port');
Client side code:
public static void main(String[] args) {
Socket socket = null;
OutputStreamWriter osw;
String str = "Hello World";
try {
socket = new Socket(**[serverIP]**, 65432);
osw =new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
osw.write(str, 0, str.length());
} catch (IOException e) {
System.err.print(e);
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论