SocketException:连接被主机软件中止

时间:2019-05-09 14:08:41

标签: c# python unity3d tcp raspberry-pi

我已经编写了典型的TCP / IP程序(unity3d上的c#客户端和raspberry上的python服务器)。客户端通过按钮将命令发送到raspberry,然后服务器通过激活继电器来响应。当我第一次运行服务器并将客户端连接到服务器时,一切都很好,但是如果我关闭了客户端的连接,然后将其重新连接到服务器并单击任何按钮,则会发送命令,但连接会发送已在服务器上关闭,并且仅当我重新运行服务器时我才能发送其他命令。它显示统一的错误消息:“ SocketException:连接被您的主机软件中止了” 有人可以帮助我解决这个问题吗? 这是我的统一代码:

using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using UnityEngine.UI;

public class Control : MonoBehaviour
{

public string IP = "192.168.8.100";
public int Port = 6704;
public byte[] dane;
public Socket client;
public InputField inputfield;
public int etat;
public string data;
public byte[] data1;
public Text display;




public void Forward_Click()
{

    data = "1";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);


}
public void Back_Click()
{


    data = "2";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);


}
public void Right_Click()
{

    data = "3";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);


}
public void Left_Click()
{


    data = "4";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);

}
public void R_Turn_Click()
{

    data = "5";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);



}
public void L_Turn_Click()
{


    data = "6";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);

}

public void FR_Click()
{


    data = "7";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);


}

public void FL_Click()
{
    data = "8";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1); }

public void OnRelease()
{ data = "0";
    data1 = System.Text.Encoding.ASCII.GetBytes(data);
    client.Send(data1);
    Debug.Log("button not pressed");
}

 public void Connecting()
{
client =
new Socket(AddressFamily. InterNetwork, 
System.Net.Sockets.SocketType.Stream, ProtocolType.Tcp);
    client.Connect(IP, Port);
    display.text = "got connection";
    Changing();


}


public void Changing()
{ byte[] b = new byte[1024];
    int k = client.Receive(b);//recive data from port coming from python script 
    string szReceived = System.Text.Encoding.ASCII.GetString(b, 0, k);
    if (client.Connected)
    {
        Debug.Log("Getting data from Python ");
        Debug.Log(szReceived);//showing data on the unity log
    }
    else
    {
        Debug.Log(" Not Connected");

    }
}


void Start()
{
        }

void Update()
{

     }
}
public void Disconnect()
{
    client.Close();
    display.text = "Disconnect";
}

}

0 个答案:

没有答案