socket.io-client客户端链接没没提示成功有源码
发布于 8 年前 作者 renzhe20092584 4638 次浏览 来自 问答

1. 服务端代码

var net=require("net");

function serverSocket(){
    var server = net.createServer(function(socket){
        
        console.log("client connected! %j:%j", socket.remoteAddress, socket.remotePort);

        socket.on("data",function(data){
            console.log("recived from client:",data.toString());
        });

        socket.on("close",function(had_error){
            if(!had_error){
                console.log("client closed success! %j:%j",socket.remoteAddress,socket.remotePort);
            }
            else{
                console.log("client close error! %j:%j",socket.remoteAddress,socket.remotePort);
            }
        });
        socket.on("error",function(err){
            console.log("!!!err!!!",err);
        });
        socket.on("connection",function(data){
            console.log("connection ");
        });

        
        //客户端登录监听
        socket.on("login",function(data){
            console.log('client login');
            socket.emit('login_result', {errcode:0,errmsg:"客户端登录成功"});
        });
    });


    server.listen({
        port:8889
    },function(){
        var address = server.address();
        console.log(" opened server on address %j ",address);
    });

    var a=1;
}
serverSocket();

2.客户端代码

var io = require('socket.io-client');

var socket = io("ws://localhost:8889");

socket.on('connection', function(){
	console.log('connection');
    
    client.emit("login", {msg:"客户端请求登录"});
});

socket.on('connect', function(){
    console.log('connect');
});
socket.on('open',function(){
	console.log('open'); 
});
socket.on('disconnect', function(){
    console.log('disconnect');
});
socket.on('reconnect', function(transport_type,reconnectionAttempts){
    console.log('reconnect*********',transport_type,reconnectionAttempts);
});


//登录结果
socket.on('login_result',function(data){
    console.log('login_result'); 
});

3.客户端没有提示链接成功 客户端 没有任何打印 服务器端

client connected! "::ffff:127.0.0.1":55241
recived from client: GET /socket.io/?EIO=3&transport=polling&t=Llnq5--&b64=1 HTTP/1.1
User-Agent: node-XMLHttpRequest
Accept: */*
Host: localhost:8889
Connection: close
8 回复

哪位大哥帮忙解决一下不知道那出问题啦

可能发射了信息,但是还没监听,换下顺序,或者用process.nextTick试试

你的client connected位置不对,应该放在connect监听事件里。慢慢来,把不需要的代码都去掉,连接成功了再慢慢加。

习惯了socket.io,原生的.net模块没试验过 socket.io 要发送和监听配合使用的 //服务端 emit(‘事件名a’,data)

//客户端 on(‘事件名a’,function(data){ console.log(data); })

@gfafei 好的谢谢我试试

@nasaplayer 好的谢谢我试试

回到顶部