当前,我正在运行此代码,该代码将JSON客户端数据发送到C#服务器,但是客户端和服务器都需要在同一台计算机上运行。我想知道是否有一种方法可以将客户端中的数据发送到另一台计算机上的服务器(假设在同一局域网中)?无需在同一台计算机上同时运行服务器和客户端代码,我想在另一台计算机上运行它,并使客户端通过网络将数据发送到C#服务器代码。我下面主要显示了Client&Server程序中使用的一些代码。我希望多台计算机运行客户端代码,并将Kinect联合的JSON数据发送到C#服务器。
客户:
// Connect to the WebSocket server!
var socket = new WebSocket("ws://localhost:8001");
socket.onopen = function (event)
{
label.innerHTML = "Connection open";
}
//Display the skeleton joints.
for (var i = 0; i < jsonObject.skeletons.length; i++) {
for (var j = 0; j < jsonObject.skeletons[i].joints.length; j++)
{
var joint = jsonObject.skeletons[i].joints[j];
context.fillStyle = "#FF0000";
context.beginPath();
context.arc(joint.x * 400 +320, (-joint.y) * 400 +240, 5, 0, Math.PI * 2, true);
console.log(joint.name);
context.closePath();
context.fill();
}
}
}
else if (event.data instanceof Blob)
{
var blob = event.data;
window.URL = window.URL || window.webkitURL;
var source = window.URL.createObjectURL(blob);
camera.src = source;
window.URL.revokeObjectURL(source);
}
}
服务器:
namespace WebSockets.Server
{
public static class BodySerializer
{
[DataContract]
class JSONSkeletonCollection
{
[DataMember(Name = "skeletons")]
public List<JSONSkeleton> Skeletons { get; set; }
}
[DataContract]
class JSONSkeleton
{
[DataMember(Name = "id")]
public string ID { get; set; }
[DataMember(Name = "joints")]
public List<JSONJoint> Joints { get; set; }
}
[DataContract]
class JSONJoint
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "x")]
public double X { get; set; }
[DataMember(Name = "y")]
public double Y { get; set; }
[DataMember(Name = "z")]
public double Z { get; set; }
}
public static string Serialize(this List<Body> skeletons, CoordinateMapper mapper, Mode mode)
{
JSONSkeletonCollection jsonSkeletons = new JSONSkeletonCollection { Skeletons = new List<JSONSkeleton>() };
foreach (var skeleton in skeletons)
{
JSONSkeleton jsonSkeleton = new JSONSkeleton
{
ID = skeleton.TrackingId.ToString(),
Joints = new List<JSONJoint>()
};
foreach (Joint joint in skeleton.Joints.Values)
{
jsonSkeleton.Joints.Add(new JSONJoint
{
Name = joint.JointType.ToString(),
X = joint.Position.X,
Y = joint.Position.Y,
Z = joint.Position.Z
});
}
jsonSkeletons.Skeletons.Add(jsonSkeleton);
}
return Serialize(jsonSkeletons);
}
private static string Serialize(object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
}
当前输出(在同一台计算机上同时运行服务器和客户端代码):