• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by SQRL · Jun 09, 2014 at 12:37 PM · c#networkingjavasocket

Data keeps "hanging". TCP client/server

Hey!
I've created a remote controller app for android for my game. I'm using TCP for sending my data but there are some irregularities with the connection. Every now and then the server stops receiving for a couple of seconds and then starts again.
I should say that networking is very new to me, so sorry if this is very basic stuff..

Here's the send code android client:

 @Override
     public void run() {
 
         //Keep in a loop as long as the running variable is true
         while(running)
         {
             //Try catch block to catch exceptions for the networking code
             try{
                 data1[0]=currentPlayer;
                 data1[1]=panL;
                 data1[2]=tiltL;
                 data1[3]=panR;
                 data1[4]=tiltR;
                 data1[5]=accX;
                 data1[6]=accY;
                 data1[7]=accZ;
                 data1[8]=sendPause;
                 
                 for(int i=0; i<=9;i++){
                     buf1[i]=(byte)data1[i];                    
                 }
                 socket = new Socket(ipAddress, 1338);
                 out = socket.getOutputStream(); 
                 dos = new DataOutputStream(out);
 
                 dos.write(buf1, 0, buf1.length);
                 dos.flush();
                 socket.close();
 
                 synchronized(this){
                     this.wait(30);
                 }
             
                 }catch(Exception e)
                 {
                     Log.e("TCP", "Error",e);
                 }
             }
             
         }

Here's the receiving server code:

 private void HandleClient(TcpClient client){  
         NetworkStream clientStream=client.GetStream();
         using(MemoryStream messageStream=new MemoryStream())
         {
             byte[] inbuffer=new byte[65536];
             if(clientStream.CanRead)
             {
                 do
                 {
                     int bytesRead=clientStream.Read(inbuffer, 0, inbuffer.Length);
                     messageStream.Write(inbuffer, 0, bytesRead);
                 }
                 while(clientStream.DataAvailable);
 
                 byte[] msg=messageStream.GetBuffer();
                 int[] stream=new int[9];
                 
                 for(int i=0; i<=8; i++){
                     stream[i]=msg[i];
                     if(stream[i]==255)stream[i]=-1;
                     if(stream[i]==254)stream[i]=-2;
                     if(stream[i]==253)stream[i]=-3;
                     if(stream[i]==252)stream[i]=-4;
                     if(stream[i]==251)stream[i]=-5;
                     if(stream[i]==250)stream[i]=-6;
                     if(stream[i]==249)stream[i]=-7;
                     if(stream[i]==248)stream[i]=-8;
                     if(stream[i]==247)stream[i]=-9;
                     if(stream[i]==246)stream[i]=-10;
                     if(stream[i]==245)stream[i]=-11;
                     if(stream[i]==244)stream[i]=-12;
                 }
                 packetID=msg[0];
                 switch(packetID){
                 case 1:
                     p1.joyLx = stream[1];
                     .....
                     p1.pause = stream[8];
                     p1.active=true;
                     break;
                 case 4:
                     p4.joyLx = stream[1];
                     ....
                     p4.pause = stream[8];
                     p4.active=true;
                     break;
                 }
 
             }
             else{
                 Debug.Log("Sorry.  You cannot read from this NetworkStream.");
             }
 
         }

Please tell me if you need more samples or anything and sorry if I'm not following protocols here. This is my first post.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image meat5000 ♦ · Jun 16, 2014 at 08:38 AM 0
Share

Watch all those Auto-Syncs hounding your connection ;)

avatar image SQRL · Jun 17, 2014 at 07:22 PM 0
Share

Doesn't help unfortunately :/ Thanks though.

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by SQRL · Jul 02, 2014 at 10:29 AM

FIXED IT!! I had to move the socket creation and closing out from the running loop so that it instead kept being open for the whole session. Besides this I also had to account for the negative bytes in C# in using sbytes.

 private void HandleClient(TcpClient client){
     try{
         byte[] bytes = new byte[256];
         sbyte[] sbytes;
  
         while(true) 
         {
             NetworkStream stream = client.GetStream();
             int i;
             while((i = stream.Read(bytes, 0, bytes.Length))!=0) 
             {   
                 sbytes = new sbyte[bytes.Length];
                 Buffer.BlockCopy(bytes, 0, sbytes, 0, bytes.Length);
                 packetID=bytes[0];
                 switch(packetID){
                 case 1:
                     p1.joyLx = sbytes[1];
 [...]

Hope this helps someone else. Cheers

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image magonicolas · Oct 22, 2017 at 09:49 PM 0
Share

Hello, please help me, $$anonymous$$y TCP connection is never connected on an android, here is my code: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;

 using System.Collections.Generic;
 using System.Text.RegularExpressions;
 using System.Runtime.Serialization.Formatters.Binary;
 using System;
 using System.IO;
 using Newtonsoft.Json;
 using System.Net;
 using System.Net.Sockets;
 using UnityEngine.Networking;
 
 
 
 public class Sock$$anonymous$$an : $$anonymous$$onoBehaviour {
 
     public Text myText;
 
     private bool socketReady;
     private TcpClient socket;
     private NetworkStream stream;
     private StreamWriter writer;
     private StreamReader reader;
 
     void Start() {
         print("Start");
         ConnectToServer();
     }
 
     public void ConnectToServer() {
         print("Setup");
         myText.text = "Setup...";
         if(socketReady)
             return;
         String host = "192.168.0.15";
         Int32 port = 8080;n
 
         try {
             print("Enter Try");
             myText.text = "Enter Try...";
             socket = new TcpClient(host, port);
             stream = socket.GetStream();
             writer = new StreamWriter(stream);
             reader = new StreamReader(stream);
             socketReady = true;
             myText.text = "Connected!";
             Send("{ \"type\": \"video\", \"value\": \"2.mp4\"}");
         } catch {}
     }
 
     private void Update() {
         if(socketReady) {
             if(stream.DataAvailable) {
                 string data = reader.ReadLine();
                 if(data != null) 
                     OnIncomingData(data);
             }
         }
     }
 
     private void OnIncomingData(string data) {
         print("Server: " + data);
     }
 
     private void Send(string data) {
         myText.text = "Will send";
         if (!socketReady) {
             writer.WriteLine(data);
             writer.Flush();
             myText.text = "Sent";
         }
     }
 }
 
avatar image
0

Answer by fholm · Jun 16, 2014 at 08:36 AM

Start by enabling no_delay on both sockets (just Google "TCP nodelay").

Then you can use a packet sniffer like wire shark to see if data arrives on the server.a

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image SQRL · Jun 17, 2014 at 07:58 PM 0
Share

Thanks for helping out. I tried the TCP nodelay on both the server and client but it didn't help. With the help of Wireshark I was able to find out that every time my data flow is interrupted I get an error saying either:

TCP 77 [TCP Retransmission] 44591 > wmc-log-svc [FIN, PSH, AC$$anonymous$$] Seq=1 Ack=1 Win=14656 Len=11 TSval=4069865 TSecr=345023

or

TCP 66 [TCP Previous segment not captured] 50455 > wmc-log-svc [FIN, AC$$anonymous$$] Seq=12 Ack=1 Win=14656 Len=0 TSval=4069881 TSecr=345165

Google tells me it can be caused by bad connection but I've encountered the problem on several networks. Could I be sending too many packets or something??

avatar image fholm · Jun 18, 2014 at 05:27 AM 0
Share

Its possible your flooding the network with too much data yes, its really hard to diagnose these issues without having physical access to the machines and network.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

24 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unity with sockets c# 0 Answers

Chat system is not working 1 Answer

Checking internetReachability from another Thread 1 Answer

LLAPI vs. pure C#.NET sockets 3 Answers

C# TcpListener is reachable only from local 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges