Simple chat app

Hello,

I’m trying to make a simple chat application. I used this code in Visual Studio and it worked great. In Unity it doesn’t work and I don’t know why. The interface shows, but it doesn’t connect and I can’t send messages. I start the application twice on one PC, I use the same IP address, and for first I use port 80, and for second port 81.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;

public class UnityChat : MonoBehaviour {

    private Rect windowRect = new Rect(200, 200, 300, 430);
    private string messBox = "", messageToSend = "";
    private string textLocalIP, textRemoteIP = "";
    private string textLocalPort = "", textRemotePort = "";

    Socket sck;
    EndPoint epLocal, epRemote;
    byte[] buffer;

    private void define()
    {
        //set up socket
        sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    }


    private void OnGUI()
    {
        windowRect = GUI.Window (1, windowRect, windowFunc, "Chat");
    }

    private void windowFunc(int id)
    {
        GUILayout.Box (messBox, GUILayout.Height (300));

        GUILayout.BeginHorizontal ();
        messageToSend = GUILayout.TextField (messageToSend);
        if(GUILayout.Button("Send", GUILayout.Width(75)))
        {
            buttonSend();
        }
        GUILayout.EndHorizontal ();
        GUILayout.BeginHorizontal ();
        textLocalIP = GetLocalIP ();
        textLocalIP = GUILayout.TextField (textLocalIP);
        textLocalPort = GUILayout.TextField (textLocalPort);
        GUILayout.EndHorizontal ();
        GUILayout.BeginHorizontal ();
        textRemoteIP = GUILayout.TextField (textRemoteIP);
        textRemotePort = GUILayout.TextField (textRemotePort);
        GUILayout.EndHorizontal ();
        if(GUILayout.Button("Connect"))
        {
            connect();
        }

        GUI.DragWindow(new Rect(0 ,0, Screen.width, Screen.height));
    }

    private string GetLocalIP()
    {
        IPHostEntry host;
        host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
                return ip.ToString();
        }
        return "127.0.0.1";

    }

    private void connect()
    {
        //binding the socket
        epLocal = new IPEndPoint(IPAddress.Parse(textLocalIP), Convert.ToInt32(textLocalPort));
        sck.Bind(epLocal);
        //Connecting to remote IP
        epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIP), Convert.ToInt32(textRemotePort));
        sck.Connect(epRemote);
        //Listening the specific port
        buffer = new byte[1500];
        sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        messBox = textLocalIP + "\n" + textRemoteIP + "\n" + textLocalPort + "\n" + textRemotePort;

    }

    private void MessageCallBack(IAsyncResult aResult)
    {
        try
        {
            byte[] receivedData = new byte[1500];
            receivedData = (byte[])aResult.AsyncState;
            //Converting byte[] to string
            ASCIIEncoding aEncoding = new ASCIIEncoding();
            string receivedMessage = aEncoding.GetString(receivedData);
           
            //Adding this message into Listbox
            messBox =  "Friend: " + receivedMessage;
           
            buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
        }
        catch (Exception exp)
        {
            //Debug.Log(exp.ToString());
        }
    }

    private void buttonSend()
    {
        //Convert string message to byte
        ASCIIEncoding aEncoding = new ASCIIEncoding();
        byte[] sendingMessage = new byte[1500];
        sendingMessage = aEncoding.GetBytes(messageToSend);
        //Sending the Encoded message
        sck.Send(sendingMessage);
        //adding to the listbox
        messBox = "Me: " + messageToSend;


    }



    }

What’s your build target? Some of them don’t support sockets (e.g. WebGL, Webplayer(?)) :frowning:

I would like to use it on PC and Android.

I thought it will be easy for experienced Unity programmers.

From just looking at it? No. You need to debug. Step through the code and find out what’s not happening that should. Or, instrument your code with a whole lot of Debug.Logs. Either way, you just need to find out how your mental model of what’s happening differs from what is actually happening.

Most of us use plugins for networking tasks, like UNet or Photon. What you want is an experienced network programmer. You might have better luck on stack overflow or some site related directly to networking.

Translation: I only have a vague idea of what a socket is and can’t help you here.

Thank you for your responses.
I think I understand your point of view.

As I said earlier, in Visual Studio this method works great. In Unity there are no errors, but I simply can’t send or receive messages. I guess it has something to do with start() or update().

Well that’s a good point. I see a MonoBehaviour with a bunch of private methods, no MonoBehaviour callbacks implemented, and no public methods… how are those private methods supposed to be called?

EDIT: Wait, no, you’ve implemented one callback: OnGUI (which by the way is more or less deprecated since Unity 4.6). So I guess that’s how it’s supposed to work.

I still recommend stepping through your code with the debugger, or using Debug.Log to make sure the code is actually executing as you think it is.

1 Like