gpt4 book ai didi

使用 Socket.io 的 Java 应用程序

转载 作者:行者123 更新时间:2023-12-01 06:12:25 25 4
gpt4 key购买 nike

我正在我的网站上使用 socket.io 进行聊天。我还喜欢编写一个小型 Java 应用程序作为此聊天的独立版本。

虽然使用 javascript 的网站工作正常,但我无法让 java 应用程序工作。

网站聊天如下所示:

codepen.io/dreadkopp/pen/zvqEXB

Java 应用程序现在看起来像这样:

package chat;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

public class chat {


public static void main(String[] args ) throws MalformedURLException{


String url = "http://yoshi.dynu.com:3000";
SocketIO socket = new SocketIO();

socket.connect(url , new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}

@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}

@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}

@Override
public void onConnect() {
System.out.println("Connection established");
}

@Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
}
});

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

socket.emit("chat message", "test");
}
}

使用这个.jar:github.com/Gottox/socket.io-java-client

运行程序时,我收到“握手错误”,服务器 http 响应代码:URL http://yoshi.dynu.com:3000/socket.io/1/ 为 400 .

因此,当连接到 http://yoshi.dynu.com:3000/socket.io/1/ 时通过浏览器我得到响应。

服务器通过nodejs使用以下javascript运行:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);



io.on('connection', function(socket){
socket.on('chat message', function(msg){

var parts = new Array(2);
parts = msg.split("ID: ");
var ID = parts[1];
msg = parts[0];


console.log('incomming message from ' + ID + ': ' + msg);
io.emit('who', ID);
if (ID != "support") {
io.emit('support' + ' message', msg);
console.log('sent to support: ' + msg);
io.emit(ID + ' message', msg);
console.log('sent to ' + ID + ' :' + msg);
}

if (ID == "support") {
var temp = new Array(2);
temp = msg.split(":");
target = temp[0];
targetmsg = msg.slice(msg.indexOf(":"));
targetmsg = targetmsg.slice(targetmsg.indexOf(" "));


io.emit(ID + ' message', msg);
console.log('sent to ' + ID + ': ' + msg);
io.emit(target + ' message', targetmsg);
console.log('sent to ' + target + ': ' + targetmsg);
}
});
});


http.listen(3000, function(){
console.log('listening on port 3000 \n' + 'awaiting messages and files...');
});

io.on('connection', function(socket){
console.log('a user connected');
});

有人知道为什么它不起作用吗?我现在尝试了 2 天来运行此应用程序,但没有成功:/

最佳答案

您的Java代码是正确的;我复制并为我工作。也许你的 URL 变量是错误的。这是我的 Nodejs 服务器代码:

var express = require("express"),
http = require("http"),
app = express(),
server = http.createServer(app),
path = require('path');
var bodyParser = require('body-parser');
var oracledb = require('oracledb');
var SimpleOracleDB = require('simple-oracledb');
SimpleOracleDB.extend(oracledb);
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.set("views", __dirname + "/public");
app.configure(function () {
app.use(express.static(__dirname));
});
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');

app.get("/pedidosNotificaciones", function (req, res) {
res.render("index1.html", {title: "pedidosNotificaciones"});
});
//app.get('/', function (req, res) {
// res.sendfile(__dirname + '/index1.html');
//});

server.listen(3004);
console.log("Notificaciones servidor en el puerto 3004");

//PRODUCCION
var connAttrs = {
user: "xxxx",
password: "xxxx",
connectString: "xxxxxx"

};
/*
var connectData110 = {
user: "xxxx",
password: "xxxx",
connectString: "//10.21.80.110:1521/BDname"
};

*/
var io = require("socket.io").listen(server);
io.sockets.on('connection', function (socket) {
socket.on('hayCambioDeEstatus', function () {
console.log("abrio un cliente....");
socket.emit("NotificacionDeCambio", "1");
socket.broadcast.emit("NotificacionDeCambio", "1");
});
socket.on('fugasRegistradas', function (idCuenta) {
var uno=0;
oracledb.getConnection(connAttrs, function (err, connection) {
if (err) {
console.log("Error al conectar con la BD....");
uno=1;
return;
}
connection.execute("SELECT FU.IDFUGA,U.NOMBRE AS LEVANTO,ES.DESCRIPCION ESTATUS,FU.FECHAREGISTRO,"
+ " FU.HORAENVIO,FU.HORACONFIRMADO,"
+ " FU.REPORTA,FU.TELEFONOREPORTA,FU.OBSERVACIONES,CA.CANAL"
+ " FROM FG_FUGAS FU"
+ " INNER JOIN CT_CANALES CA ON CA.IDCANAL=FU.IDCANAL"
+ " INNER JOIN CT_ESTATUS ES ON ES.IDESTATUS=FU.IDESTATUS"
+ " INNER JOIN SG_USUARIOS U ON U.IDUSUARIO=FU.IDUSUARIO"
+ " WHERE IDCUENTA="+idCuenta, {}, {
outFormat: oracledb.OBJECT
}, function (err, result) {
if (err) {
console.log("ERROR...EN LA CONSULTA.");
} else {
// console.log(result.rows);
socket.emit('registro', result.rows);
}
connection.release( function (err) {
if (err) {
console.error(err.message);
} else {
console.log("fugasRegistradas.... Conexion liberada");
}
});
});
});
});

socket.on('folioAlternativo', function () {
var uno=0;
oracledb.getConnection(connAttrs, function (err, connection) {
if (err) {
console.log("Error al conectar con la BD....");
uno=1;
return;
}
connection.execute("SELECT SUBSTR(MAX(FOLIOSERVICIO),1,5) AS ALTERNATIVO FROM FG_TERMINADAS WHERE FOLIOSERVICIO >= '50000'", {}, {
outFormat: oracledb.OBJECT
}, function (err, result) {
if (err) {
console.log("ERROR...EN LA CONSULTA.");
} else {
console.log(result.rows);
socket.emit('ultimo', result.rows);
}
connection.release( function (err) {
if (err) {
console.error(err.message);
} else {
console.log("folioAlternativo.... Conexion liberada");
}
});
});
});
});

});

关于使用 Socket.io 的 Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32683040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com