本文整理汇总了C#中WebSocket.Close方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocket.Close方法的具体用法?C# WebSocket.Close怎么用?C# WebSocket.Close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类WebSocket
的用法示例。
在下文中一共展示了WebSocket.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Start
// Use this for initialization
IEnumerator Start () {
WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8080/websocket"));
yield return StartCoroutine(w.Connect());
int i = 0;
w.SendString(PackMessage("Hi there", i));
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
Message msg = UnpackMessage (reply);
Debug.Log ("Received: " + msg.msg + ", " + msg.no);
w.SendString (PackMessage ("Hi there", i));
}
if (w.error != null)
{
Debug.LogError ("Error: " + w.error);
break;
}
++i;
yield return 0;
}
w.Close();
}
示例2: Start
/// <summary>
/// Start the Birb Client.
/// </summary>
/// <returns>Nothing right now.</returns>
IEnumerator Start()
{
gameStateManager = GetComponent<GameStateManager>();
Uri server = new Uri("ws://birb.herokuapp.com");
Uri localhost = new Uri("ws://localhost:5000");
socket = new WebSocket(server);
callbacks = new Dictionary<BirbMessageCode, Callback>();
yield return StartCoroutine(socket.Connect());
int i = 0;
// Testing
//RunUnitTests();
while (true)
{
string reply = socket.RecvString();
if (reply != null)
{
Debug.Log("Received: " + reply);
Process(reply);
}
if (socket.Error != null)
{
Debug.LogError("Error: " + socket.Error);
break;
}
yield return 0;
}
socket.Close();
}
示例3: ExecuteCommand
public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
{
string description;
if (!session.ProtocolProcessor.VerifyHandshake(session, commandInfo, out description))
{
session.Close(session.ProtocolProcessor.CloseStatusCode.ProtocolError, description);
return;
}
session.OnHandshaked();
}
示例4: WsClient
public WsClient () {
bool success = TestConnection();
if (success) {
Debug.Log ("Server check ok");
string server = String.Format("wss://{0}:{1}/", ip, port );
using (conn = new WebSocket (server,"game"));
conn.Connect ();
conn.OnOpen += (sender, e) => conn.Send ("Server Connected");
conn.OnError += (sender, e) => {
Debug.Log("Websocket Error");
conn.Close ();
};
conn.OnClose += (sender, e) => {
Debug.Log("Websocket Close");
conn.Close ();
};
} else {
Debug.Log ("Server check failed");
return;
}
conn.SslConfiguration.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => {
// Do something to validate the server certificate.
Debug.Log ("Cert: " + certificate);
return true; // If the server certificate is valid.
};
}
示例5: ExecuteCommand
public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
{
//Close handshake was sent from client side, now got a handshake response
if (session.StateCode == WebSocketStateConst.Closing)
{
session.CloseWithoutHandshake();
return;
}
//Got server side closing handshake request, send response now
var statusCode = commandInfo.CloseStatusCode;
if (statusCode <= 0)
statusCode = session.ProtocolProcessor.CloseStatusCode.NoStatusCode;
session.Close(statusCode, commandInfo.Text);
}
示例6: Start
// Use this for initialization
IEnumerator Start () {
WebSocket w = new WebSocket(new Uri("ws://192.168.1.206:8888/ws"));
yield return StartCoroutine(w.Connect());
w.SendString("UnityTest");
int i=0;
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
Debug.Log ("Received: "+reply);
w.SendString("UnityTest " + i++);
}
if (w.Error != null)
{
Debug.LogError ("Error: "+w.Error);
break;
}
yield return 0;
}
w.Close();
}
示例7: ExecuteCommand
public override void ExecuteCommand(WebSocket session, WebSocketCommandInfo commandInfo)
{
//Close handshake was sent from client side, now got a handshake response
if (session.State == WebSocketState.Closing)
{
//Not NormalClosure
if (commandInfo.CloseStatusCode != session.ProtocolProcessor.CloseStatusCode.NormalClosure &&
(commandInfo.CloseStatusCode > 0 || !string.IsNullOrEmpty(commandInfo.Text)))
{
session.FireError(new Exception(string.Format("{0}: {1}", commandInfo.CloseStatusCode, commandInfo.Text)));
}
session.CloseWithouHandshake();
return;
}
//Got server side closing handshake request, send response now
var statusCode = commandInfo.CloseStatusCode;
if (statusCode <= 0)
statusCode = session.ProtocolProcessor.CloseStatusCode.NoStatusCode;
session.Close(statusCode, commandInfo.Text);
}
示例8: Start
// Use this for initialization
IEnumerator Start()
{
WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:3000"));
yield return StartCoroutine(w.Connect());
w.SendString("Hi there");
int i = 0;
while(true)
{
string reply = w.RecvString();
if(reply != null)
{
Debug.Log("Received: " + reply);
w.SendString("Hi there" + i++);
}
if(w.Error != null)
{
Debug.LogError("Error: " + w.Error);
break;
}
yield return 0;
}
w.Close();
}
示例9: Main
private static void Main(string[] args)
{
var client = new WebSocket("127.0.0.1", 8080);
client.Opened += (sender, eventArgs) => Console.WriteLine("Connection open!");
client.Closed += (sender, eventArgs) => Console.WriteLine("Connection closed");
client.MessageReceived += (sender, eventArgs) => Console.WriteLine(((WebSocketEventArgs)eventArgs).Data);
var exit = false;
while (!exit)
{
var cmd = Console.ReadLine();
switch (cmd)
{
case "/close":
client.Close();
break;
case "/exit":
exit = true;
break;
case "/open":
client.Open();
break;
case "/send":
client.SendMdnString();
break;
default:
Console.WriteLine("Unknown command " + cmd);
break;
}
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
示例10: Start
// Use this for initialization
IEnumerator Start()
{
WebSocket w = new WebSocket(new Uri("ws://178.62.242.126:8000/"));
yield return StartCoroutine(w.Connect());
int i=0;
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
float newAccelerationTarget = parseAcceleration(reply);
if(newAccelerationTarget > 0.1f){
accelerationTargetReached = false;
accelerationTarget = 1.0f;
}
moveCharacter();
Debug.Log ("Received: "+reply);
}
if (w.Error != null)
{
Debug.LogError ("Error: "+w.Error);
break;
}
yield return 0;
}
w.Close();
}
示例11: StartWebSocket_CR
// Use this for initialization
IEnumerator StartWebSocket_CR()
{
WebSocket w = new WebSocket(new Uri("ws://128.2.236.66:3000"));
yield return StartCoroutine(w.Connect());
w.SendString("Ctrl Connected");
while (true)
{
string res = w.RecvString();
if (res != null)
{
#if UNITY_EDITOR
Debug.Log("Received: " + res);
#endif
//w.SendString("Hi there" + i++);
char[] delimiterChars = { ' ' ,'\t' };
string[] parseStr = res.Split(delimiterChars);
switch(parseStr[0]){
case "m+":{
_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, true, parseStr);
break;
}
case "m-":{
_crowdSim.globalAttentionMean = SetValueFromString(_crowdSim.globalAttentionMean, false, parseStr);
break;
}
case "d+":{
_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, true, parseStr);
break;
}
case "d-":{
_crowdSim.globalAttentionStDev = SetValueFromString(_crowdSim.globalAttentionStDev, false, parseStr);
break;
}
case "u+":{
_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, true, parseStr);
break;
}
case "u-":{
_crowdSim.seatPosAttentionUpper = SetValueFromString(_crowdSim.seatPosAttentionUpper, false, parseStr);
break;
}
case "l+":{
_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, true, parseStr);
break;
}
case "l-":{
_crowdSim.seatPosAttentionLower = SetValueFromString(_crowdSim.seatPosAttentionLower, false, parseStr);
break;
}
}
w.SendString("|Unity> currStat: m=" + _crowdSim.globalAttentionMean + ", dev=" + _crowdSim.globalAttentionStDev
+ ", A_up=" + _crowdSim.seatPosAttentionUpper + ", A_Low=" + _crowdSim.seatPosAttentionLower + "." );
//w.SendString("|Unity> blar blar" + res);
}
if (w.Error != null)
{
#if UNITY_EDITOR
Debug.Log("Error: " + w.Error);
#endif
break;
}
yield return 0;
}
w.Close();
}
示例12: OutgoingMessagePump
/// <summary>
/// Subscribes to the provided <paramref name="outgoing"/> stream, sending all events to the provided <paramref name="socket"/>.
/// </summary>
/// <param name="outgoing">The outgoing stream.</param>
/// <param name="socket">
/// The socket.
/// </param>
/// <returns>
/// The <see cref="Task"/> which will complete when either the observable completes (or errors) or the socket is closed (or errors).
/// </returns>
private static async Task OutgoingMessagePump(IObservable<string> outgoing, WebSocket socket)
{
var completion = new TaskCompletionSource<int>();
var subscription = new IDisposable[] { null };
Action complete = () =>
{
subscription[0]?.Dispose();
completion.TrySetResult(0);
};
// Until the socket is closed, pipe messages to it, then complete.
subscription[0] = outgoing.TakeWhile(_ => !socket.IsClosed).SelectMany(
next => socket.Send(ResponseKind.Next + next).ToObservable(),
error => socket.Send(ResponseKind.Error + JsonConvert.SerializeObject(error.ToDetailedString())).ToObservable(),
() =>
{
if (socket.IsClosed)
{
return Observable.Empty<Unit>();
}
// Send and close the socket.
var send = socket.Send(ResponseKind.Completed.ToString(CultureInfo.InvariantCulture)).ToObservable();
return send.SelectMany(_ => socket.Close((int)WebSocketCloseStatus.NormalClosure, "onCompleted").ToObservable());
}).Subscribe(_ => { }, _ => complete(), complete);
await completion.Task;
}
示例13: ListenToMtgox
private static void ListenToMtgox()
{
var ws = new WebSocket("ws://" + Dns.GetHostAddresses("websocket.mtgox.com").First().ToString() + ":80/mtgox", "*");
var observableWs = new ObservableWebsocket(ws);
if (!ws.Connect())
{
Console.WriteLine("Not connected");
Console.ReadLine();
}
else
{
Console.Clear();
Connected(observableWs);
ws.Close();
}
}
示例14: Start
//.........这里部分代码省略.........
onPlayerConnected(other);
break;
}
case specUpdatePosition:
{
uint id = BitConverter.ToUInt32(reply, 4);
float x = BitConverter.ToSingle(reply, 8);
float y = BitConverter.ToSingle(reply, 12);
float z = BitConverter.ToSingle(reply, 16);
var pos = new Vector3(x, y, z);
Player other = null;
if (player.id == id)
break;
if (otherPlayers.TryGetValue(id, out other)) {
//Debug.Log(other.name + " is now at position " + pos);
other.pos = pos;
if (onPlayerMoved != null)
onPlayerMoved(other);
}
break;
}
case specMessage:
{
uint id = BitConverter.ToUInt32(reply, 4);
string message = Encoding.Unicode.GetString(reply, 8, reply.Length - 8);
string name = null;
if (id == player.id)
name = player.name;
if (name == null) {
Player other = null;
if (otherPlayers.TryGetValue(id, out other)) {
name = other.name;
if (onPlayerMessage != null)
onPlayerMessage(other, message);
}
}
if (name != null)
Debug.Log(name + ": " + message);
else
Debug.Log("player" + id + ": " + message);
break;
}
case specHeartbeat:
{
SendHeartbeatResponse();
break;
}
case specUpdateHealth:
{
uint id = BitConverter.ToUInt32(reply, 4);
float health = BitConverter.ToSingle(reply, 8);
Player updatedPlayer = null;
if (id == player.id)
{
updatedPlayer = player;
} else
{
Player other = null;
if (otherPlayers.TryGetValue(id, out other))
{
updatedPlayer = other;
}
}
if (updatedPlayer != null)
{
updatedPlayer.health = health;
if (onPlayerUpdateHealth != null)
onPlayerUpdateHealth(updatedPlayer, health);
}
break;
}
case specUpdateState:
{
uint id = BitConverter.ToUInt32(reply, 4);
int stateSize = reply.Length - 8;
byte[] state = new byte[stateSize];
Buffer.BlockCopy(reply, 8, state, 0, stateSize);
Player updatedPlayer = null;
if (id == player.id) {
updatedPlayer = player;
} else {
Player other = null;
if (otherPlayers.TryGetValue(id, out other)) {
updatedPlayer = other;
}
}
if (updatedPlayer != null) {
updatedPlayer.state = state;
if (onPlayerUpdateState != null)
onPlayerUpdateState(updatedPlayer, state);
}
break;
}
}
} else {
yield return 0;
}
}
w.Close();
}
示例15: StartCommunicator
/// Use this for initialization
IEnumerator StartCommunicator()
{
WebSocket w = new WebSocket(new Uri("ws://192.168.33.138:8080"));
if(!testLocally) {
yield return StartCoroutine(w.Connect());
w.SendString("Hi there, I'm the communicator");
}
int i=0;
while (true)
{
sendingIntervalCountdown -= Time.deltaTime;
if(sendingIntervalCountdown < 0) {
sendingIntervalCountdown = sendingInterval;
String toSend = "{\"x\":"+ball.position.x+",\"y\":"+ball.position.z+",\"z\":"+ball.position.y+"}";
Debug.Log(toSend);
if(!testLocally) {
w.SendString (toSend);
}
}
string reply = null;
if(!testLocally) {
reply = w.RecvString();
} else {
reply = localTestCommand;
localTestCommand = null;
}
if (reply != null)
{
Debug.Log ("Received: "+reply);
Vector3 force = Vector3.zero;
/*if(reply != null && reply.Length == ) {
if(reply[0] == '#') {
}
}*/
switch(reply) {
case "jump":
force = new Vector3(0, 300, 0);
break;
case "left":
force = new Vector3(500, 0, 0);
break;
case "right":
force = new Vector3(-500, 0, 0);
break;
case "forward":
force = new Vector3(0, 0, 500);
break;
case "backward":
force = new Vector3(0, 0, -500);
break;
case "color":
force = new Vector3(0, 0, -500);
break;
}
//Debug.Log (force);
ball.GetComponent<Rigidbody>().AddForce(force);
//w.SendString("Hi there"+i++);
}
if (!testLocally && w.error != null)
{
Debug.LogError ("Error: "+w.error);
break;
}
yield return 0;
}
w.Close();
}