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!
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 🙂
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! 🙂
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.
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.
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 🙂
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 :)’
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. 🙂
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)
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.
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.
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.
There’s actually quite a lot of samples/tutorials out there if you do some googling.
This one is pretty basic but if I remember right it doesn’t keep listening to connections
This is a quick C# server that I whooped together from some sample a while ago. It can handle multiple clients sending many requests. This one has a basic example of when the client sends the string “get time” to the server, the server responds with the time.
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!!!
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?
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.
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.
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.
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
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?
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?
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.
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
Oh I so totally forgot to reply to this after I approved it. For socket connections I found this for you:
A Socket does not know what a directory is. You can connect to a server (e.g. http://www.example.com:8080), and that’s it. For WWW requests you can do folders as well though
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.
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 🙂
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 ?
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 🙂
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!
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 🙂
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
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.
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.
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.
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
LikeLike
nevermind, I feel silly now, I noticed the missing parenthesis of that line right after I posted.
Now all I need to do is find this CielaSpike resource you are referencing
LikeLike
aaand I just needed to comment out that ‘using’ line. it’s working like a charm, thank you!
LikeLike
missing ) correct if (GUILayout.Button (“Connect”))
LikeLike
Thanks for pointing that out! Must have missed it when I re-wrote the version for the tutorial.
LikeLike
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!
LikeLike
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 🙂
LikeLike
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! 🙂
LikeLiked by 1 person
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
LikeLike
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.
LikeLike
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
LikeLike
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 🙂
LikeLike
So that’s using your code? Sorry bit of a noob with c# 🙂
Chris
LikeLike
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 :)’
LikeLike
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
LikeLiked by 1 person
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)
LikeLike
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.
LikeLike
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.
LikeLiked by 1 person
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.
LikeLike
Hey,
Thanks for the information.
How can I write my C++ windows socket server to test this.
Can you provide some reference.!
~Thanks
LikeLike
There’s actually quite a lot of samples/tutorials out there if you do some googling.
This one is pretty basic but if I remember right it doesn’t keep listening to connections
https://msdn.microsoft.com/en-us/library/windows/desktop/ms737593(v=vs.85).aspx
LikeLike
This is a quick C# server that I whooped together from some sample a while ago. It can handle multiple clients sending many requests. This one has a basic example of when the client sends the string “get time” to the server, the server responds with the time.
http://kadri.synamicd.com/Unity/Program.cs
LikeLike
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!!!
LikeLiked by 1 person
Thank you for your kind words 🙂 I’m glad to have been able to help out!
LikeLike
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?
LikeLike
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.
LikeLike
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.
LikeLike
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.
LikeLike
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
LikeLike
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?
LikeLike
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!
LikeLike
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.
LikeLike
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!
LikeLike
Oh I so totally forgot to reply to this after I approved it. For socket connections I found this for you:
A Socket does not know what a directory is. You can connect to a server (e.g. http://www.example.com:8080), and that’s it. For WWW requests you can do folders as well though
LikeLike
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.
LikeLike
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 🙂
LikeLike
oh leedilaav, thank you so much.
i made the server in Matlab, it’s working really good.
LikeLiked by 1 person
I’m glad you found it helpful 🙂
LikeLike
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.
LikeLiked by 1 person
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 🙂
LikeLike
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!
LikeLiked by 1 person
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 🙂
LikeLike
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
LikeLike
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.
LikeLike
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.
LikeLike
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.
LikeLike