我正在使用android和kinect制作双应用程序。我希望能够从kinect向Android应用程序发送通知。有人告诉我,实现这一目标的最佳方法是设置一个简单的tcp服务器。我尝试使用此< link>上的教程进行设置。然而,该教程对我来说不够具有描述性,我无法使其工作。发布它的人基本上发布了几段代码而没有任何关于组装它们的说明。我需要有人来指导我设置这个服务器,或者我需要一个指向详细教程的链接。我已经在网上搜索了几个小时,但我没有找到任何有用的东西,这就是我在这里问的原因。
答案 0 :(得分:1)
以下是我认为他在该教程中要做的事情:
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace TCPServerTutorial
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
//you'll have to find a way to pass this arg
private void SendBack(TcpClient tcpClient)
{
NetworkStream clientStream = tcpClient.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();
}
}
}
但那只是我。他只谈过一个班级,所以假设他的所有职能都在那个班级是合乎逻辑的。
对于客户端代码,他几乎只给你一个函数的代码(当然是在C#中),它会将一些字节发送到一个IP地址(也就是运行服务器的机器的IP)。您可以将此函数放在任何C#类中,并以您希望的任何方式调用它。他已经硬编码了IP地址和要发送的消息,但这些很容易成为传递给函数的参数。
private void SendToServer(){
TcpClient client = new TcpClient();
//IP of the server: currently loopback, change to whatever you want
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
//Message being sent: "Hello Server!"
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();
}