Unity3D and TCP/IP Socket Connections

Since the blog has moved you can find all the files and the full tutorial HERE

Β 

46 thoughts on “Unity3D and TCP/IP Socket Connections

  1. fodakahn says:

    this exactly the kind of resource I was looking for, but I’m getting a lot of parsing errors on socketScript.cs 😦

    Particularly around if (GUILayout.Button (“Connect”) at line 41

    Like

  2. fodakahn says:

    I’m having a strange issue, I’m hoping you can provide some insight.

    The server I’m using is done in AutoHotKey and uses winsock to handle TCP stuff. I have an autohotkey client that totally sends strings to that server no problem. When I send text to it using the Unity client you wrote, my server reads it as Chinese characters!

    Like

    • leedilaav says:

      Hey, I’m not familiar with AutoHotKey at all. Maybe the server is trying to decrypt/encrypt what you send. I was using this code with a very simple test C++ server and everything was being sent and received correctly. So the weird characters, I assume, have something to do with the server, the AutoHotKey server and client have probably already built in scripts to understand each other correctly.
      I’m glad you found this useful though πŸ™‚

      Like

      • fodakahn says:

        Thanks for the reply. Actually, I figured it out. My autohotkey server converts the UTF-8 it was getting into ANSI and trying to display that. I had to convert it back to UTF-8. Weird. Works perfectly now! πŸ™‚

        Liked by 1 person

  3. Chris says:

    Hi, I am looking for the code that will enable me to open a socket so i can control some lighting equipment, So once connected i can send and receive commands, Can i use your script for this? I hope you do not mind helping out.

    Chrid

    Like

    • leedilaav says:

      Hey Chris, how would you normally control the equipment? This script basically allows you to connect to a remote “server” application to handle whats being sent and received.

      Like

      • Chris says:

        Thank you for getting back to me. I have used Putty Telnet to connect and send and receive commands, i was hoping to do that in unity so i can make a sexy interface to control the lights πŸ™‚

        Chirs

        Like

      • leedilaav says:

        Yeah you can definitely do that. Just got to set up the ip/hostname and ports and then send the commands through the Unity client πŸ™‚

        Like

  4. Chris shead says:

    So that’s using your code? Sorry bit of a noob with c# πŸ™‚

    Chris

    Like

    • leedilaav says:

      yeah in TCPConnection.cs you just got to define your ip/hostname and port. The you can attach socketScript.cs to the main camera, you don’t have to attach the TCPConnection.cs anywhere. Then you should already be able to connect and use the text field to send a message to your receiving end :)’

      Like

  5. Chris says:

    Heya Leedilaav,
    Your code is working well thank you so much, I am changing a few things to work with the Unity UI events and its great i can control my lights from buttons etc, I now just trying to change the code so I can add an event when it receives a message back. πŸ™‚

    Thank you for your help

    Chris

    Liked by 1 person

    • ali says:

      Could you tell us how did you overcome?
      I repeatedly got this error:
      NullReferenceException: Object reference not set to an instance of an object:
      TCPConnection.readSocket () (at Assets/scripts/TCPConnection.cs:52)
      socketScript.SocketResponse () (at Assets/scripts/socketScript.cs:121)
      socketScript.Update () (at Assets/scripts/socketScript.cs:55)

      Like

      • leedilaav says:

        Hey Ali,
        I wasn’t getting that error when I tested it so I ran it again. So the reason why it happens is when the machine actively refuses the connection then the variable theStream is never set so you’d get the nullreference (at least this was happening to me, not sure if its the same in your case).

        I adjusted the following in the readSocket() method

        if (theStream != null && theStream.DataAvailable) {

        which then never tried to get any data when the stream object is not set up.

        I hope this helps. If you continue to have issues let me know, I’d be more than happy to help out.

        Like

  6. okky says:

    Hi, I’ve just test your code, but I can connect to server. I use same IP with your code but i’m having this log.
    Socket error:System.Net.Sockets.SocketException: Connection refused

    Can you help me, why this could happen? Thank you.

    Liked by 1 person

    • leedilaav says:

      Hey okky,
      this specific error could be caused by 2 specific reasons. The server is found by the client but cannot connect to it since either the server is not listening to that specific port you are trying to connect to, or its a (router) firewall issue. For me, connecting to myself was no issue when the server is listening to the same port as the client is connecting to. When I wanted my other computer to be able to connect to this server, I had to manually configure my routers firewall to redirect and allow connections for that specific port to connect to the server’s machine in the local network. I hope this is helpful.

      Like

  7. Rohan Kadolkar says:

    Hey,

    Thanks for the information.

    How can I write my C++ windows socket server to test this.
    Can you provide some reference.!

    ~Thanks

    Like

  8. Lara says:

    Thank you so much! I’ve been trying to write a udp LLAPI code for weeks to connect with LabVIEW and it didn’t work no matter what. I tried your code and it worked perfectly! Seriously thank you so much for posting this and being so helpful in the comments! YOU ROCK!!!

    Liked by 1 person

    • leedilaav says:

      Thank you for your kind words πŸ™‚ I’m glad to have been able to help out!

      Like

      • Lara says:

        My one question is about sending a message. LabVIEW is able to send a message to unity with no problem, but when I type a message in and click send on unity I will not receive the message on LabVIEW. The dubug log will tell me the client sent the message but I don’t see the message showing up on LabVIEW. Is the problem on the LabVIEW side you think?

        Like

      • leedilaav says:

        Does labVIEW have some sort of way to show what it receives from? I have never used it so I have no idea what it is/does. My assumption would be that you need to somehow output everything that is sent/received within labView and then go from there.

        Like

  9. Lara Riem says:

    I used a program called wireshark to see if the message was being sent from the computer using unity, and I didn’t see it. So from what I understand unity isn’t sending the message/string.

    Like

    • leedilaav says:

      it might require a different line ending depending where it’s sending. It both sends and receives correctly when it’s interacting with my custom server.

      String tmpString = theLine + “\r\n”;
      Depending on the system, the receiving end might expect a different line ending and thus not showing that it’s getting anything. I can’t recall what the different ones were, \r\n is for windows though.
      There’s probably ways to making it universal but I haven’t needed to do that just yet. You could try \r or \n separately and see if either works.

      Like

  10. Caio says:

    Hey Leedilaav
    Excuse my lack of knowledge (I’m very new to the scene), how do i know if your codes worked? I’m pressing play on unity, but my console its empty. No errors and no messages. Probably is something very silly. Sorry for that.
    Just to let you know, my websocket server was built only to send messages/inputs, and what I’m trying to do is an app to read them remotely.
    Thanks for everything

    Like

    • leedilaav says:

      Hey Caio,
      You need to actualy click on the Connect button and then it should tell you in the console that it’s attempting to connect. Once connection is made, you can then send and receive messages. On your servers end I guess if you don’t expect any messages from the client it should just detect once the connection is live to send whatever you need. But your console definitely shouldn’t be empty. Do you see the UI buttons? Did you attach socketScript to your game object on the scene?

      Like

      • Caio says:

        Hey! Thanks for the fast feedback!
        What I did was: attached the socketScript to the maincamera and pressed play… However, now that you mentioned the Connect button I’ll try to look at it.
        off topic: Are you familiar to SockJS and STOMP protocol?

        Thanks for everything!

        Like

      • leedilaav says:

        Hope the buttons appeared. Unity has changed the UI system quite a bit since I wrote this but I think the buttons can still be created via script like that.
        In regards to your off topic question, sadly I’m not familiar with those.

        Like

  11. Caio says:

    Thanks Leedilaav!!!! So, your scripts worked perfectly! The button showed up I pressed connect and I think I got a connection through my server. Beasides that I got one question, since the object TcpClient is composed by conHost and conPort, I’d like to know if I’m able to use on conHost my “127.0.0.1/something”. English its not my native language and I dont know if I am expressing myself clear. I got an error when I try to connect my IPserver/apidata.

    Error: Socket error:System.Net.Sockets.SocketException: No such host is known

    Thanks in advance, youve been very kind!

    Like

  12. Saiphan says:

    Many thanks, works like a charm.
    Though mind that in ‘Update’, you should add a check for ‘if(socketReady)’ or something to get rid of the error that happens when you are not connected. Also there is a ‘using statement’ above which is not relevant and shows an error. You can just comment it out or delete it.
    Thanks again.

    Like

    • leedilaav says:

      Oh yeah there are definitely some flaws in the old version, I’ve been refactoring this code actually in the last few weeks and I’ll probably post the updates for this soon. Thank you for the feedback πŸ™‚

      Like

  13. John Prada says:

    oh leedilaav, thank you so much.
    i made the server in Matlab, it’s working really good.

    Liked by 1 person

  14. Flowzer says:

    Hi leedilaav !

    First of all, thanks for sharing your code !

    So I have test your code in my project and I have some issue…
    I have a server write in javascript which send json data on the command prompt.
    What I am trying to do is to connect my unity project with the server to read the json data. And I would like to know if is it possible with your code ?

    Thank you very much !

    Sorry, I repost it as a real reply of your work.

    Liked by 1 person

    • leedilaav says:

      No problem Flowzer, I deleted the other comment πŸ™‚
      Um, it’s definitely possible since JSON data is basically a specifically formatted string, so what you need on the client side is a way of parsing that data.
      Since .NET doesn’t (as far as I know) come with a JSON parser, you’d need to either write one or download one made by someone else. There should be plenty of them out there, just got to google a bit πŸ™‚

      Like

  15. Emma says:

    Really girls can code !!!
    Your code had been very usefull for my work project. Now I can make communication between Unity and ROS lisbraries,
    A lot of thanks!

    Liked by 1 person

    • leedilaav says:

      Thank you Emma! πŸ™‚
      And I’m happy it’s been helpful!

      I haven’t got around to posting here for a while. Just been awfully busy with work and kids and such but hopefully I can post some more cool stuff here soon, a few things I’ve been working on slowly πŸ™‚

      Like

  16. Zain says:

    Hi,
    awsome work. I have been trying to link my c++ code with unity and came across your code. I am using zmq to send data on specific port say 5555 and set it in unity too. But I dont recieve any data in console on unity.
    Can I use zmq ? or I need some other server

    [SERVER]οΏ½
    UnityEngine.Debug:Log(Object)
    socketScript:SocketResponse() (at Assets/socketScript.cs:134)
    socketScript:Update() (at Assets/socketScript.cs:57)
    This is my output. I would really appreciate some help

    Like

    • leedilaav says:

      Hey Zain,
      It definitely looks like you are getting something (the Object), I don’t know how your ZMQ is sending data exactly so it’s a little difficult to help but I assume it’s in some sort of array format. Would have to know how the server sends the data to properly output/use it on the client.

      Like

  17. MAFE says:

    Hi, do you have a tutorial to get started in servers, and i donΒ΄t know were i should start to do a comunication between Unity and Wii Balance, would you please gime ve some advice for it?
    Thank you so much.

    Like

    • leedilaav says:

      hey MAFE,
      If you just do a quick google search on c# socket server example you should find example server code by Microsoft. Sadly I don’t know much about how Wii Balance works so without actually doing research on that I can’t help with that, sorry.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s