sooon sooon - 1 month ago 14
Node.js Question

Unity3d - Node.js tcp connection, Client did not update immediately

I am testing

as TCP server and
as client for my up coming project.

I create a simple chat interface with
that can send and receive data from the server. Everything seems to work fine until I test with 2 clients, one in
Unity editor
and another with
Unity application
, whenever I send the message, the server immediately pickup and display in
. But the client side only update the display interface when I click to focus on the client, be it
Unity editor
or the
Unity application

Below are my codes:


net = require('net');
var clients = [];

net.createServer(function (socket) { = socket.remoteAddress + ":" + socket.remotePort

socket.write("Welcome " + + "\n");
broadcast( + " joined the chat\n", socket);

socket.on('data', function (data) {
broadcast( + "> " + data, socket);

socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast( + " left the chat.\n");

function broadcast(message, sender) {
clients.forEach(function (client) {
if (client === sender) return;


// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");


using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Net.Sockets;
using System.IO;

public class client : MonoBehaviour {

private bool socketReady;
private TcpClient socket;
private NetworkStream stream;
private StreamWriter writer;
private StreamReader reader;

public Text servermessage;
public InputField input;

// Use this for initialization
void Start () {
ConnectToServer ();

// Update is called once per frame
void Update () {
string data = reader.ReadLine ();
if(data != null){
OnIncomingData (data);

public void ConnectToServer(){

string host = "";
int port = 5000;

socket = new TcpClient(host,port);
stream = socket.GetStream();
writer = new StreamWriter(stream);
reader = new StreamReader(stream);
socketReady = true;

Debug.Log("socket :"+ reader.ToString());
catch (System.Exception e)
Debug.Log("socket error :"+ e);


private void OnIncomingData(string data){
Debug.Log ("server : "+ data);
servermessage.text = data;

public void OnOutgoingData(string data){
if (!socketReady)
if (input.text == "") {
writer.WriteLine (data);
} else {
writer.WriteLine (input.text);
writer.Flush ();
input.text = "";

What is missing? How can I make it that I can see the immediate update on all my client interface?


This is not caused by your code, but due to the Unity editor. By default the unity editor does not run applications in the background.

You can turn run-in-background on inEdit > Project Settings > Settings-Player

There should be a field Run in background. Turn it on, and it should update even when you are not focused

See Also Run In background