Writing and reading using socket












1















This is my code



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

public class s_TCP : MonoBehaviour {

internal Boolean socketReady = false;

TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "198.57.44.231";
Int32 Port = 1337;
string channel = "testingSona";

void Start () {
setupSocket();
//string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
string msg = "Sending By Sona";
writeSocket(msg);
readSocket();

}
void Update () {
//readSocket();
}

public void setupSocket() {
try {
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
}
}
public void writeSocket(string theLine) {
if (!socketReady)
return;
String foo = theLine + "rn";
theWriter.Write(foo);
theWriter.Flush();

}
public String readSocket() {
if (!socketReady)
return "";
if (theStream.DataAvailable){
string message = theReader.ReadLine();
print(message);print(12345);
return theReader.ReadLine();
}
else{print("no value");
return "";
}

}
public void closeSocket() {
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}


}



Connection created. But message not writing into server and reading



How can i do it










share|improve this question





























    1















    This is my code



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

    public class s_TCP : MonoBehaviour {

    internal Boolean socketReady = false;

    TcpClient mySocket;
    NetworkStream theStream;
    StreamWriter theWriter;
    StreamReader theReader;
    String Host = "198.57.44.231";
    Int32 Port = 1337;
    string channel = "testingSona";

    void Start () {
    setupSocket();
    //string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
    string msg = "Sending By Sona";
    writeSocket(msg);
    readSocket();

    }
    void Update () {
    //readSocket();
    }

    public void setupSocket() {
    try {
    mySocket = new TcpClient(Host, Port);
    theStream = mySocket.GetStream();
    theWriter = new StreamWriter(theStream);
    theReader = new StreamReader(theStream);
    socketReady = true;
    }
    catch (Exception e) {
    Debug.Log("Socket error: " + e);
    }
    }
    public void writeSocket(string theLine) {
    if (!socketReady)
    return;
    String foo = theLine + "rn";
    theWriter.Write(foo);
    theWriter.Flush();

    }
    public String readSocket() {
    if (!socketReady)
    return "";
    if (theStream.DataAvailable){
    string message = theReader.ReadLine();
    print(message);print(12345);
    return theReader.ReadLine();
    }
    else{print("no value");
    return "";
    }

    }
    public void closeSocket() {
    if (!socketReady)
    return;
    theWriter.Close();
    theReader.Close();
    mySocket.Close();
    socketReady = false;
    }


    }



    Connection created. But message not writing into server and reading



    How can i do it










    share|improve this question



























      1












      1








      1


      2






      This is my code



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

      public class s_TCP : MonoBehaviour {

      internal Boolean socketReady = false;

      TcpClient mySocket;
      NetworkStream theStream;
      StreamWriter theWriter;
      StreamReader theReader;
      String Host = "198.57.44.231";
      Int32 Port = 1337;
      string channel = "testingSona";

      void Start () {
      setupSocket();
      //string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
      string msg = "Sending By Sona";
      writeSocket(msg);
      readSocket();

      }
      void Update () {
      //readSocket();
      }

      public void setupSocket() {
      try {
      mySocket = new TcpClient(Host, Port);
      theStream = mySocket.GetStream();
      theWriter = new StreamWriter(theStream);
      theReader = new StreamReader(theStream);
      socketReady = true;
      }
      catch (Exception e) {
      Debug.Log("Socket error: " + e);
      }
      }
      public void writeSocket(string theLine) {
      if (!socketReady)
      return;
      String foo = theLine + "rn";
      theWriter.Write(foo);
      theWriter.Flush();

      }
      public String readSocket() {
      if (!socketReady)
      return "";
      if (theStream.DataAvailable){
      string message = theReader.ReadLine();
      print(message);print(12345);
      return theReader.ReadLine();
      }
      else{print("no value");
      return "";
      }

      }
      public void closeSocket() {
      if (!socketReady)
      return;
      theWriter.Close();
      theReader.Close();
      mySocket.Close();
      socketReady = false;
      }


      }



      Connection created. But message not writing into server and reading



      How can i do it










      share|improve this question
















      This is my code



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

      public class s_TCP : MonoBehaviour {

      internal Boolean socketReady = false;

      TcpClient mySocket;
      NetworkStream theStream;
      StreamWriter theWriter;
      StreamReader theReader;
      String Host = "198.57.44.231";
      Int32 Port = 1337;
      string channel = "testingSona";

      void Start () {
      setupSocket();
      //string msg = "__SUBSCRIBE__"+channel+"__ENDSUBSCRIBE__";
      string msg = "Sending By Sona";
      writeSocket(msg);
      readSocket();

      }
      void Update () {
      //readSocket();
      }

      public void setupSocket() {
      try {
      mySocket = new TcpClient(Host, Port);
      theStream = mySocket.GetStream();
      theWriter = new StreamWriter(theStream);
      theReader = new StreamReader(theStream);
      socketReady = true;
      }
      catch (Exception e) {
      Debug.Log("Socket error: " + e);
      }
      }
      public void writeSocket(string theLine) {
      if (!socketReady)
      return;
      String foo = theLine + "rn";
      theWriter.Write(foo);
      theWriter.Flush();

      }
      public String readSocket() {
      if (!socketReady)
      return "";
      if (theStream.DataAvailable){
      string message = theReader.ReadLine();
      print(message);print(12345);
      return theReader.ReadLine();
      }
      else{print("no value");
      return "";
      }

      }
      public void closeSocket() {
      if (!socketReady)
      return;
      theWriter.Close();
      theReader.Close();
      mySocket.Close();
      socketReady = false;
      }


      }



      Connection created. But message not writing into server and reading



      How can i do it







      c# sockets unity3d






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 24 '18 at 20:24









      Uwe Keim

      27.6k32132213




      27.6k32132213










      asked Jul 18 '13 at 9:26









      SonaSona

      59652454




      59652454
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.



          The following code does not work correctly:



          public String readSocket() {
          if (!socketReady)
          return "";
          if (theStream.DataAvailable)
          return theReader.ReadLine();
          return "";
          }


          This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:



          theStream.ReadTimeout = 1;


          And then, you can use something like:



          public String readSocket() {
          if (!socketReady)
          return "";
          try {
          return theReader.ReadLine();
          } catch (Exception e) {
          return "";
          }
          }


          This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.






          share|improve this answer
























          • Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

            – saward
            Aug 5 '14 at 23:03













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17719541%2fwriting-and-reading-using-socket%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.



          The following code does not work correctly:



          public String readSocket() {
          if (!socketReady)
          return "";
          if (theStream.DataAvailable)
          return theReader.ReadLine();
          return "";
          }


          This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:



          theStream.ReadTimeout = 1;


          And then, you can use something like:



          public String readSocket() {
          if (!socketReady)
          return "";
          try {
          return theReader.ReadLine();
          } catch (Exception e) {
          return "";
          }
          }


          This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.






          share|improve this answer
























          • Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

            – saward
            Aug 5 '14 at 23:03


















          0














          I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.



          The following code does not work correctly:



          public String readSocket() {
          if (!socketReady)
          return "";
          if (theStream.DataAvailable)
          return theReader.ReadLine();
          return "";
          }


          This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:



          theStream.ReadTimeout = 1;


          And then, you can use something like:



          public String readSocket() {
          if (!socketReady)
          return "";
          try {
          return theReader.ReadLine();
          } catch (Exception e) {
          return "";
          }
          }


          This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.






          share|improve this answer
























          • Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

            – saward
            Aug 5 '14 at 23:03
















          0












          0








          0







          I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.



          The following code does not work correctly:



          public String readSocket() {
          if (!socketReady)
          return "";
          if (theStream.DataAvailable)
          return theReader.ReadLine();
          return "";
          }


          This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:



          theStream.ReadTimeout = 1;


          And then, you can use something like:



          public String readSocket() {
          if (!socketReady)
          return "";
          try {
          return theReader.ReadLine();
          } catch (Exception e) {
          return "";
          }
          }


          This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.






          share|improve this answer













          I think you have taken this code from http://answers.unity3d.com/questions/15422/unity-project-and-3rd-party-apps.html, but I think there is an error in this code. I'll repeat here what I posted there.



          The following code does not work correctly:



          public String readSocket() {
          if (!socketReady)
          return "";
          if (theStream.DataAvailable)
          return theReader.ReadLine();
          return "";
          }


          This caused me a headache for quite few hours. I think that checking DataAvailable on the stream is not a reliable way to check if there is data to be read on the streamreader. So you do not want to check for DataAvailable. However, if you just remove that, then the code will block on ReadLine when there is no more to read. So instead, you need to set a timeout for reading from the stream, so that you won't wait longer than (say) a millisecond:



          theStream.ReadTimeout = 1;


          And then, you can use something like:



          public String readSocket() {
          if (!socketReady)
          return "";
          try {
          return theReader.ReadLine();
          } catch (Exception e) {
          return "";
          }
          }


          This code isn't perfect, I still need to improve it (e.g., check what kind of exception was raised, and deal with it appropriately). And maybe there's a better way overall to do this (I experimented with using Peek(), but the -1 it returns I suspect is for when the socket closes, and not just when there is no more data to read for now). However, this should solve problems with the posted code, like those I was having. If you're finding data is missing from the server, then it's probably sitting in your reader stream, and won't be read until new data is sent from the server and stored in the stream such that theStream.DataAvailable returns true.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '13 at 14:47









          sawardsaward

          1811113




          1811113













          • Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

            – saward
            Aug 5 '14 at 23:03





















          • Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

            – saward
            Aug 5 '14 at 23:03



















          Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

          – saward
          Aug 5 '14 at 23:03







          Just in case anyone is interested, the above approach is not the correct way to handle sockets. I cannot remember why, though. Also, I had trouble with ReadTimeout setting being ignored on windows machines. There's a better way to handle sockets lurking around on a Unity wiki somewhere, iirc.

          – saward
          Aug 5 '14 at 23:03






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17719541%2fwriting-and-reading-using-socket%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          404 Error Contact Form 7 ajax form submitting

          How to know if a Active Directory user can login interactively

          TypeError: fit_transform() missing 1 required positional argument: 'X'