GVKun编程网logo

socket.io没有发送给客户端(socket客户端收不到消息)

14

对于想了解socket.io没有发送给客户端的读者,本文将是一篇不可错过的文章,我们将详细介绍socket客户端收不到消息,并且为您提供关于Android服务端将位置信息发送给客户端、Android服

对于想了解socket.io没有发送给客户端的读者,本文将是一篇不可错过的文章,我们将详细介绍socket客户端收不到消息,并且为您提供关于Android 服务端将位置信息发送给客户端、Android 服务端将位置信息发送给客户端的实现、C#使用Socket实现一个socket服务器与多个socket客户端通信、io.sockets.socket(socket_id).emit()-没有方法'socket'的有价值信息。

本文目录一览:

socket.io没有发送给客户端(socket客户端收不到消息)

socket.io没有发送给客户端(socket客户端收不到消息)

我正在尝试创建一个简单的脚本,以便每次文件更新时都将文件中的数据发送到客户端。我已经测试过,发现该文件已被读取,但是客户端什么也没收到。控制台中没有错误。我对socket.io相当陌生。

node.js代码

var app = require(''express'')();var http = require(''http'').Server(app);var io = require(''socket.io'')(http);var fs = require("fs");var port = process.env.PORT || 3000;app.get(''/'', function(req, res){    res.sendFile(__dirname + ''/popup.html'');});fs.watchFile("assets/popup.json", {interval:100}, function(curr, prev){    fs.readFile("assets/popup.json",{encoding:"utf8"}, function(err, data){        io.emit("popup", data)    })});http.listen(port, function(){    console.log(''listening on *:'' + port);});

客户代码

var socket = io();socket.on(''popup'', function(msg){    alert("hello")});

答案1

小编典典

每当事情无法正常进行时,您都需要诉诸“调试模式”。在这种模式下,您需要收集所有可能发生的事件,并从中学到什么。为此,请将以下代码添加到客户端:

var socket = io();socket.on(''popup'', function(msg){    console.log("hello: ", msg)});socket.on(''connection'', function() {    console.log("client connected");});socket.on(''connect_error'', function(err) {    console.log("client connect_error: ", err);});socket.on(''connect_timeout'', function(err) {    console.log("client connect_timeout: ", err);});

这些消息都记录在socket.io Github站点上的客户端文档中,您可以随时通过谷歌搜索“
socket.io github”来找到它们。

然后,查看页面加载后在浏览器控制台中看到的内容。如果您不知道如何在使用的浏览器中打开浏览器控制台,请在Google上进行查找。页面加载时,您需要查看调试控制台。

仅供参考,我们假设您已在此代码之前通过脚本标记将socket.io加载到页面中。如果不是,该错误也会显示在控制台中。


然后,OP收到此错误:

client connect_error:     Error: server error at Socket.onPacket (socket.io-1.2.0.js:1)       at XHR.<anonymous> (socket.io-1.2.0.js:1)       at XHR.Emitter.emit (socket.io-1.2.0.js:1)       at XHR.Transport.onPacket (socket.io-1.2.0.js:1)       at callback (socket.io-1.2.0.js:2)       at Object.exports.decodePayload (socket.io-1.2.0.js:2)       at XHR.Polling.onData (socket.io-1.2.0.js:2)       at Request.<anonymous> (socket.io-1.2.0.js:2)       at Request.Emitter.emit (socket.io-1.2.0.js:1)       at Request.onData (socket.io-1.2.0.js:2)

好,进展。您如何在客户端页面中加载socket.io?似乎您的客户端和服务器中的socket.io版本不匹配。您应该这样做:

<script src="/socket.io/socket.io.js"></script>

然后您的服务器将向客户端页面提供完全相同版本的socket.io。另外,由于此错误报告了客户端socket.io
1.2.0,因此服务器上安装了哪个版本的socket.io?

Android 服务端将位置信息发送给客户端

Android 服务端将位置信息发送给客户端

一、问题

Android 服务端将位置信息发送给客户端

二、环境

AndroidStudio Eclipse

三、代码实现

服务端Servlet调用Dao层在数据库中查找数据,在servlet中将查找到的数据汇集成json字符串(json数组形式)。

服务端:

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException {
//		response.setContentType("text/plain; charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		ServerToParentDao stpDao = new ServerToParentDao();
//		String num = mtpDao.query();
//		System.out.println(num);
		PrintWriter out = response.getWriter();
		StringBuffer sb = new StringBuffer();
		sb.append('[');
		List<Address> addrList = stpDao.queryOne();
		for (Address address : addrList) {
			sb.append('{').append("\"id\":").append("" + address.getId() + "").append(",");
			sb.append("\"latitude\":").append("\"" + address.getLatitude() + "\"").append(",");
			sb.append("\"longitude\":").append("\"" + address.getLongitude() + "\"").append(",");
			sb.append("\"time\":\"").append(address.getTime());
			sb.append("\"}").append(",");
		}
		sb.deleteCharat(sb.length() - 1);
		sb.append(']');
		out.write(sb.toString());
		System.out.println(sb.toString());
//		request.setAttribute("json",sb.toString());
//		request.getRequestdispatcher("watch.jsp").forward(request, response);
//		out.write(num);
//			response.getoutputStream().write(mtpDao.query().getBytes("UTF-8"));
		out.flush();
		out.close();

//		System.err.println(request.getParameter(""));
//			System.out.println(code);
		System.out.println("连接成功");
//		PrintWriter printWriter = response.getWriter();
//		printWriter.print("客户端你好,数据连接成功!");
//		printWriter.flush();
//		printWriter.close();
	}

客户端:

sendButton.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ServerToParentServlet");
                List<NameValuePair> params = new ArrayList<NameValuePair>();
//                String str = "1";
//                params.add(new BasicNameValuePair("Code", str));
                Log.i("MY3", "Has Done");
                try {
//                    httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置请求参数项
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpResponse httpResponse = httpClient.execute(httpRequest);//执行请求返回响应
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {//判断是否请求成功
                        httpentity entity = httpResponse.getEntity();
                        if (entity != null) {
                            System.out.println("---------");
//                            System.out.println("Respone content" + EntityUtils.toString(entity, "UTF-8"));
                            Intent intent = new Intent(ParentRequest.this,MainActivity.class);
                            intent.putExtra("jsonString",EntityUtils.toString(entity, "UTF-8"));
                            startActivity(intent);
                        }
                Log.i("MY2", "Has Done");
                    } else {
                        Toast.makeText(ParentRequest.this, "没有获取到Android服务器端的响应!", Toast.LENGTH_LONG).show();
                    }
                } catch (ClientProtocolException e) {
                    e.printstacktrace();
                } catch (UnsupportedEncodingException e) {
                    e.printstacktrace();
                } catch (IOException e) {
                    e.printstacktrace();
                }
            }
        });

请求地址书写形式:http://主机IP地址:端口号/项目名/action名
HttpPost方式建立连接,HttpResponse.getEntity()获取响应信息,EntityUtils.toString(entity, “UTF-8”)将entity转为String字符串,Intent将JSON字符串传递到其他activity页面中去。


JSON字符串解析类:

public static List<Address> getAddress(String jsonStr)
            throws JSONException {
        /******************* 解析 ***********************/
        // 初始化list数组对象
        List<Address> mList = new ArrayList<Address>();
        Address address = new Address();
        JSONArray array = new JSONArray(jsonStr);
        for (int i = 0; i < array.length(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            address = new Address(jsonObject.getInt("id"),
                    jsonObject.getString("latitude"), jsonObject.getString("longitude"),
                    jsonObject.getString("time"));
            mList.add(address);
        }
        return mList;
    }

我这个是当时在做一个儿童定位写的,数据库设计没思考全面,思维比较狭隘。
应该思考到的是儿童信息表中儿童信息要跟父母表中父母信息对应起来,即这APP是给多对父母和孩子使用的,而不是一对父母与孩子。
服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。

Android 服务端将位置信息发送给客户端的实现

Android 服务端将位置信息发送给客户端的实现

一、问题

Android 服务端将位置信息发送给客户端

二、环境

AndroidStudio Eclipse

三、代码实现

服务端Servlet调用Dao层在数据库中查找数据,在servlet中将查找到的数据汇集成json字符串(json数组形式)。

服务端:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// response.setContentType("text/plain; charset=UTF-8");
 request.setCharacterEncoding("UTF-8");
 ServerToParentDao stpDao = new ServerToParentDao();
// String num = mtpDao.query();
// System.out.println(num);
 PrintWriter out = response.getWriter();
 StringBuffer sb = new StringBuffer();
 sb.append(''['');
 List<Address> addrList = stpDao.queryOne();
 for (Address address : addrList) {
  sb.append(''{'').append("\"id\":").append("" + address.getId() + "").append(",");
  sb.append("\"latitude\":").append("\"" + address.getLatitude() + "\"").append(",");
  sb.append("\"longitude\":").append("\"" + address.getLongitude() + "\"").append(",");
  sb.append("\"time\":\"").append(address.getTime());
  sb.append("\"}").append(",");
 }
 sb.deleteCharAt(sb.length() - 1);
 sb.append('']'');
 out.write(sb.toString());
 System.out.println(sb.toString());
// request.setAttribute("json",sb.toString());
// request.getRequestDispatcher("watch.jsp").forward(request, response);
// out.write(num);
//  response.getOutputStream().write(mtpDao.query().getBytes("UTF-8"));
 out.flush();
 out.close();

// System.err.println(request.getParameter(""));
//  System.out.println(code);
 System.out.println("连接成功");
// PrintWriter printWriter = response.getWriter();
// printWriter.print("客户端你好,数据连接成功!");
// printWriter.flush();
// printWriter.close();
 }

客户端:

sendButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ServerToParentServlet");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
//        String str = "1";
//        params.add(new BasicNameValuePair("Code", str));
        Log.i("MY3", "Has Done");
        try {
//          httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置请求参数项
          HttpClient httpClient = new DefaultHttpClient();
          HttpResponse httpResponse = httpClient.execute(httpRequest);//执行请求返回响应
          if (httpResponse.getStatusLine().getStatusCode() == 200) {//判断是否请求成功
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
              System.out.println("---------");
//              System.out.println("Respone content" + EntityUtils.toString(entity, "UTF-8"));
              Intent intent = new Intent(ParentRequest.this,MainActivity.class);
              intent.putExtra("jsonString",EntityUtils.toString(entity, "UTF-8"));
              startActivity(intent);
            }
        Log.i("MY2", "Has Done");
          } else {
            Toast.makeText(ParentRequest.this, "没有获取到Android服务器端的响应!", Toast.LENGTH_LONG).show();
          }
        } catch (ClientProtocolException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });

请求地址书写形式:http://主机IP地址:端口号/项目名/action名

HttpPost方式建立连接,HttpResponse.getEntity()获取响应信息,EntityUtils.toString(entity, “UTF-8”)将entity转为String字符串,Intent将JSON字符串传递到其他activity页面中去。

JSON字符串解析类:

public static List<Address> getAddress(String jsonStr)
      throws JSONException {
    /******************* 解析 ***********************/
    // 初始化list数组对象
    List<Address> mList = new ArrayList<Address>();
    Address address = new Address();
    JSONArray array = new JSONArray(jsonStr);
    for (int i = 0; i < array.length(); i++) {
      JSONObject jsonObject = array.getJSONObject(i);
      address = new Address(jsonObject.getInt("id"),
          jsonObject.getString("latitude"), jsonObject.getString("longitude"),
          jsonObject.getString("time"));
      mList.add(address);
    }
    return mList;
  }

我这个是当时在做一个儿童定位写的,数据库设计没思考全面,思维比较狭隘。

应该思考到的是儿童信息表中儿童信息要跟父母表中父母信息对应起来,即这APP是给多对父母和孩子使用的,而不是一对父母与孩子。

服务端也不应该是使用本地的,应该使用云服务器,这样就不会被同一局域网所限制。

Android 客户端将位置信息发送给服务端

代码实现

客户端:

 HttpPost httpRequest = new HttpPost("http://192.168.159.1:8080/MyAndroidServer/ChildrenToServerServlet");
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
      Date date = new Date(System.currentTimeMillis());
      String str=simpleDateFormat.format(date);
      System.out.println(str);
      params.add(new BasicNameValuePair("Time", str));
      params.add(new BasicNameValuePair("Latitude",latitude));
      params.add(new BasicNameValuePair("Longitude", longitude));
      try {
        httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//设置请求参数项
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse httpResponse = httpClient.execute(httpRequest);//执行请求返回响应
        if(httpResponse.getStatusLine().getStatusCode() == 200){//判断是否请求成功
//          Toast.makeText(ChildrenToServerActivity.this, EntityUtils.toString(httpResponse.getEntity()), Toast.LENGTH_LONG).show();
          Intent intent = new Intent();
          intent.setAction("cn.abel.action.broadcast");
          intent.putExtra("Response", EntityUtils.toString(httpResponse.getEntity()));
          context.sendBroadcast(intent);
        }else{
//          Toast.makeText(MainActivity.this, "没有获取到Android服务器端的响应!", Toast.LENGTH_LONG).show();
          Intent intent = new Intent();
          intent.setAction("cn.abel.action.broadcast");
          intent.putExtra("Response", "没有获取到Android服务器端的响应!");
          context.sendBroadcast(intent);
        }
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
params.add(new BasicNameValuePair(“Time”, str));

Time是str的变量名,用于服务端接收数据用的。
这是用来添加要传递给服务端的数据,为String字符串形式。

服务端:

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
 response.setContentType("text/plain; charset=UTF-8");
 request.setCharacterEncoding("UTF-8");
 String time = request.getParameter("Time");
 String latitude = request.getParameter("Latitude");
 String longitude = request.getParameter("Longitude");
 ChildrenToAddressDao addressDao = new ChildrenToAddressDao();
 addressDao.insert(latitude, longitude, time);
 
 System.err.println(request.getParameter("Time"));
 System.err.println(request.getParameter("Latitude"));
 System.err.println(request.getParameter("Longitude"));
 PrintWriter printWriter = response.getWriter();
 printWriter.print("客户端你好,数据连接成功!");
 printWriter.flush();
 printWriter.close();
 }

request.getParameter(“变量名”)是用来接收客户端对应变量名的数据。
addressDao.insert()是我自己定义的方法,将接收到的数据存入MySQL中。

到此这篇关于Android 服务端将位置信息发送给客户端的实现的文章就介绍到这了,更多相关Android 服务端位置信息发送给客户端内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

您可能感兴趣的文章:
  • Android socket实现原理详解 服务端和客户端如何搭建
  • Android Socket服务端与客户端用字符串的方式互相传递图片的方法
  • Android客户端与服务端交互

C#使用Socket实现一个socket服务器与多个socket客户端通信

C#使用Socket实现一个socket服务器与多个socket客户端通信

  笔记一下知识内容,原文地址:https://www.cnblogs.com/yy3b2007com/p/7476458.html

  server端代码

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace SocketServerAcceptMultipleClient
{
    public class SocketServer
    {
        // 创建一个和客户端通信的套接字
        static Socket socketwatch = null;
        //定义一个集合,存储客户端信息
        static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

        public static void Main(string[] args)
        {
            //定义一个套接字用于监听客户端发来的消息,包含三个参数(IP4寻址协议,流式连接,Tcp协议)  
            socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //服务端发送信息需要一个IP地址和端口号  
            IPAddress address = IPAddress.Parse("127.0.0.1");
            //将IP地址和端口号绑定到网络节点point上  
            IPEndPoint point = new IPEndPoint(address, 8098);
            //此端口专门用来监听的  

            //监听绑定的网络节点  
            socketwatch.Bind(point);

            //将套接字的监听队列长度限制为20  
            socketwatch.Listen(20);

            //负责监听客户端的线程:创建一个监听线程  
            Thread threadwatch = new Thread(watchconnecting);

            //将窗体线程设置为与后台同步,随着主线程结束而结束  
            threadwatch.IsBackground = true;

            //启动线程     
            threadwatch.Start();

            Console.WriteLine("开启监听。。。");
            Console.WriteLine("点击输入任意数据回车退出程序。。。");
            Console.ReadKey();
            Console.WriteLine("退出监听,并关闭程序。");
        }

        //监听客户端发来的请求  
        static void watchconnecting()
        {
            Socket connection = null;

            //持续不断监听客户端发来的请求     
            while (true)
            {
                try
                {
                    connection = socketwatch.Accept();
                }
                catch (Exception ex)
                {
                    //提示套接字监听异常     
                    Console.WriteLine(ex.Message);
                    break;
                }

                //获取客户端的IP和端口号  
                IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address;
                int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port;

                //让客户显示"连接成功的"的信息  
                string sendmsg = "连接服务端成功!\r\n" + "本地IP:" + clientIP + ",本地端口" + clientPort.ToString();
                byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                connection.Send(arrSendMsg);

                //客户端网络结点号  
                string remoteEndPoint = connection.RemoteEndPoint.ToString();
                //显示与客户端连接情况
                Console.WriteLine("成功与" + remoteEndPoint + "客户端建立连接!\t\n");
                //添加客户端信息  
                clientConnectionItems.Add(remoteEndPoint, connection);

                //IPEndPoint netpoint = new IPEndPoint(clientIP,clientPort); 
                IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint;

                //创建一个通信线程      
                ParameterizedThreadStart pts = new ParameterizedThreadStart(recv);
                Thread thread = new Thread(pts);
                //设置为后台线程,随着主线程退出而退出 
                thread.IsBackground = true;
                //启动线程     
                thread.Start(connection);
            }
        }

        /// <summary>
        /// 接收客户端发来的信息,客户端套接字对象
        /// </summary>
        /// <param name="socketclientpara"></param>    
        static void recv(object socketclientpara)
        {
            Socket socketServer = socketclientpara as Socket;

            while (true)
            {
                //创建一个内存缓冲区,其大小为1024*1024字节  即1M     
                byte[] arrServerRecMsg = new byte[1024 * 1024];
                //将接收到的信息存入到内存缓冲区,并返回其字节数组的长度    
                try
                {
                    int length = socketServer.Receive(arrServerRecMsg);

                    //将机器接受到的字节数组转换为人可以读懂的字符串     
                    string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, 0, length);

                    //将发送的字符串信息附加到文本框txtMsg上     
                    Console.WriteLine("客户端:" + socketServer.RemoteEndPoint + ",time:" + GetCurrentTime() + "\r\n" + strSRecMsg + "\r\n\n");

                    socketServer.Send(Encoding.UTF8.GetBytes("测试server 是否可以发送数据给client "));
                }
                catch (Exception ex)
                {
                    clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString());

                    Console.WriteLine("Client Count:" + clientConnectionItems.Count);

                    //提示套接字监听异常  
                    Console.WriteLine("客户端" + socketServer.RemoteEndPoint + "已经中断连接" + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n");
                    //关闭之前accept出来的和客户端进行通信的套接字 
                    socketServer.Close();
                    break;
                }
            }
        }

        ///      
        /// 获取当前系统时间的方法    
        /// 当前时间     
        static DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }
    }
}

  client端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace SocketClient
{
    public partial class Main : Form
    {
        //创建 1个客户端套接字 和1个负责监听服务端请求的线程  
        Thread threadclient = null;
        Socket socketclient = null;

        public Main()
        {
            InitializeComponent();

            StartPosition = FormStartPosition.CenterScreen;
            //关闭对文本框的非法线程操作检查  
            TextBox.CheckForIllegalCrossThreadCalls = false;

            this.btnSendMessage.Enabled = false;
            this.btnSendMessage.Visible = false;

            this.txtMessage.Visible = false;
        }

        private void btnConnection_Click(object sender, EventArgs e)
        {
            this.btnConnection.Enabled = false;
            //定义一个套接字监听  
            socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //获取文本框中的IP地址  
            IPAddress address = IPAddress.Parse("127.0.0.1");

            //将获取的IP地址和端口号绑定在网络节点上  
            IPEndPoint point = new IPEndPoint(address, 8098);

            try
            {
                //客户端套接字连接到网络节点上,用的是Connect  
                socketclient.Connect(point);
                this.btnSendMessage.Enabled = true;
                this.btnSendMessage.Visible = true;
                this.txtMessage.Visible = true;
            }
            catch (Exception)
            {
                Debug.WriteLine("连接失败\r\n");

                this.txtDebugInfo.AppendText("连接失败\r\n");
                return;
            }

            threadclient = new Thread(recv);
            threadclient.IsBackground = true;
            threadclient.Start();
        }

        // 接收服务端发来信息的方法    
        void recv()
        {
            int x = 0;
            //持续监听服务端发来的消息 
            while (true)
            {
                try
                {
                    //定义一个1M的内存缓冲区,用于临时性存储接收到的消息  
                    byte[] arrRecvmsg = new byte[1024 * 1024];

                    //将客户端套接字接收到的数据存入内存缓冲区,并获取长度  
                    int length = socketclient.Receive(arrRecvmsg);

                    //将套接字获取到的字符数组转换为人可以看懂的字符串  
                    string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
                    if (x == 1)
                    {
                        this.txtDebugInfo.AppendText("服务器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
                        Debug.WriteLine("服务器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
                    }
                    else
                    {
                        this.txtDebugInfo.AppendText(strRevMsg + "\r\n\n");
                        Debug.WriteLine(strRevMsg + "\r\n\n");
                        x = 1;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("远程服务器已经中断连接" + "\r\n\n");
                    Debug.WriteLine("远程服务器已经中断连接" + "\r\n");
                    break;
                }
            }
        }

        //获取当前系统时间  
        DateTime GetCurrentTime()
        {
            DateTime currentTime = new DateTime();
            currentTime = DateTime.Now;
            return currentTime;
        }

        //发送字符信息到服务端的方法  
        void ClientSendMsg(string sendMsg)
        {
            //将输入的内容字符串转换为机器可以识别的字节数组     
            byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
            //调用客户端套接字发送字节数组     
            socketclient.Send(arrClientSendMsg);
            //将发送的信息追加到聊天内容文本框中     
            Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
            this.txtDebugInfo.AppendText("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            //调用ClientSendMsg方法 将文本框中输入的信息发送给服务端     
            ClientSendMsg(this.txtMessage.Text.Trim());
            this.txtMessage.Clear();
        }
    }
}

 

io.sockets.socket(socket_id).emit()-没有方法'socket'

io.sockets.socket(socket_id).emit()-没有方法'socket'

如何解决io.sockets.socket(socket_id).emit()-没有方法''socket''?

在1.0中,您应该使用:

io.sockets.connected[socketid].emit();

向特定客户发出。

socket_server.sockets.socket(socket_id).emit();

已在socket.io 1.0中替换。

解决方法

我正在运行一个nodejs服务器+ express +
socket.io版本1.0.4,并且一切都在我的应用程序中按预期工作,但是我无法通过以下方式从服务器端向客户端发出消息:

socket_server.sockets.socket(socket_id).emit("message",data);

当我尝试服务器抛出以下错误时:

    TypeError: Object #<Namespace> has no method ''socket''

但我记得该代码在我的socket.io 0.7上起作用。 /0.8。 专案

我究竟做错了什么?:(

我的app.js(nodejs服务器)中的摘录:

    var express = require(''express'');
var app = express();

/* Server Start */
var server = app.listen(8080,function() {
    console.log(''Listening on port %d'',server.address().port);
});

app.set("view options",{
    layout: false
});
app.use(express.static(__dirname + ''/public''));

app.get(''/'',function(req,res) {
    res.render(''index.html'');
});

var socket_server = require(''socket.io'').listen(server);
socket_server.sockets.on(''connection'',function(client) {
// fire my emits here like: socket_server.sockets.socket(socket_id).emit("msg",data);
}

关于socket.io没有发送给客户端socket客户端收不到消息的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Android 服务端将位置信息发送给客户端、Android 服务端将位置信息发送给客户端的实现、C#使用Socket实现一个socket服务器与多个socket客户端通信、io.sockets.socket(socket_id).emit()-没有方法'socket'的相关信息,请在本站寻找。

本文标签: