1.unity服务端,接收来自winform的Picht, Yaw, Roll
///
/// scoket服务器监听端口脚本
///
public class SocketServer : MonoBehaviour
{
public GameObject obj;
private Thread thStartServer;//定义启动socket的线程
private string msg;
public float Roll,Picht,Yaw;
private String[] strArray=null;
void Start()
{
thStartServer = new Thread(StartServer);
thStartServer.Start();//启动该线程
}
void Update()
{
obj.transform.eulerAngles = new Vector3(Picht, Yaw, Roll);
}
private void StartServer()
{
const int bufferSize = 8792;//缓存大小,8192字节
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener tlistener = new TcpListener(ip, 8888);
tlistener.Start();
Debug.Log("Socket服务器监听启动......");
TcpClient remoteClient = tlistener.AcceptTcpClient();//接收已连接的客户端,阻塞方法
Debug.Log("客户端已连接!local:" + remoteClient.Client.LocalEndPoint + "<---Client:" + remoteClient.Client.RemoteEndPoint);
NetworkStream streamToClient = remoteClient.GetStream();//获得来自客户端的流
do
{
try //直接关掉客户端,服务器端会抛出异常
{
//接收客户端发送的数据部分
byte[] buffer = new byte[bufferSize];//定义一个缓存buffer数组
int byteRead = streamToClient.Read(buffer, 0, bufferSize);
if (byteRead == 0)//连接断开,或者在TCPClient上调用了Close()方法,或者在流上调用了Dispose()方法。
{
Debug.Log("客户端连接断开......");
break;
}
msg = Encoding.ASCII.GetString(buffer, 0, byteRead);//将传输过来的数据流转换为字符串
strArray = msg.Split(',');
// Roll = float.Parse(msg);
for (int i = 0; i < strArray.Length; i++)
{
Roll = float.Parse( strArray[0]);
Picht = float.Parse(strArray[1]);
Yaw = float.Parse(strArray[2]);
}
Debug.Log(msg);//显示传输过来的字符串
//tt.GetComponent
().text = msg;
}
catch(Exception ex)
{
Debug.Log("客户端异常:"+ex.Message);
break;
}
}
while (true);
}
void OnApplicationQuit()
{
thStartServer.Abort();//在程序结束时杀掉线程
}
2.在winform端代码
public partial class Form1 : Form
{
const int portNo = 8888;
private TcpClient _client;
byte[] data;
}
private void Form1_Load(object sender, EventArgs e)
{
//设置本机IP及端口号
this._client = new TcpClient();
this._client.Connect("127.0.0.1", portNo);
data = new byte[this._client.ReceiveBufferSize];
}
public void SendMessage(string message)//发送数据
{
try
{
NetworkStream ns = this._client.GetStream();
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);//将要发送的数据转化为字节流,然后发送数据
ns.Write(data, 0, data.Length);
ns.Flush();
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
}
}