Código de ejemplo de WebSocket basado en HTML5
Código de cliente:
<html><head><script>var socket;if (WebSocket en ventana) {var ws = new WebSocket(ws://127.0.0.1:8181);socket = ws;ws.onopen = function() {console. log('Conexión exitosa');};ws.onmessage = function(evt) {varceived_msg = evt.data; document.getElementById(showMes).value+=evt.data+/n;};ws.onclose = function() {alert(desconectado);};} else {alert(el navegador no admite WebSocket);}función de inicio de sesión (){ var mensaje=document.getElementById(nombre).value+:+document.getElementById(mes).value;socket.send(message);}</script></head><body><textarea filas=3 cols=30 id= showMes style=width:300px;height:500px;></textarea><br/><label>Nombre</label><input type=text id=nombre/><br/><label>Mensaje</label><input type=text id=mes/><button onclick=login();>Enviar</button></body></ HTML>
código del servidor winform:
Nota: primero es necesario presentar el paquete Fleck
usando System;usando System.Collections.Generic;usando System.Linq;usando System.Windows.Forms;usando Fleck;namespace socketService{clase parcial pública Form1: Formulario{público Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;}privado void Form1_Load(remitente del objeto, EventArgs e){//Guardar todas las conexiones var allSockets = new List<IWebSocketConnection>();//Inicializa el servidor var server = new WebSocketServer(ws://0.0.0.0:8181);//Comienza a escuchar server.Start(socket =>{//Una conexión de cliente activa el socket. OnOpen = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Connection/r/n;allSockets.Add(socket);};//La desconexión del cliente activa socket.OnClose = () =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + Disconnect/r/n ;allSockets.Remove( socket);};//Recibir mensajes enviados por el cliente socket.OnMessage = message =>{textBox3.Text += socket.ConnectionInfo.ClientIpAddress + envió un mensaje: + mensaje + /r/n;//Envía el mensaje recibido a todos los clientes allSockets.ToList().ForEach(s => s.Send(message));}; ;}}}Resumir
Lo anterior es el código de ejemplo de WebSocket basado en HTML5 presentado por el editor. Espero que le resulte útil. Si tiene alguna pregunta, déjeme un mensaje y el editor le responderá a tiempo. ¡También me gustaría agradecer a todos por su apoyo al sitio web de artes marciales VeVb!