I'm attempting to create a bare bones websocket chat room server. My client is able to connect to the server, but it is unable to send messages to the server, despite the server being in a listening state.
When the client connects, a bunch of what looks like header information gets written to the console. But when WebSocket.send() gets executed in Javascript, nothing occurs server side.
HTML:
<button id="closeSocket">disconnect</button><br />
<input id = "inputField" /><button id="sendMessage">send</button>
<div id = "output"></div>
<script type = 'text/javascript' src = 'websockets.js'></script>
Javascript:
websocket = new WebSocket("ws://127.0.0.1:80");
document.getElementById("closeSocket").onclick = closeSocket;
document.getElementById("sendMessage").onclick = sendMessage;
websocket.onopen = function(){
output("connected");
}
function sendMessage(){
output("sent: " + document.getElementById('inputField').value);
websocket.send(document.getElementById('inputField').value);
}
websocket.onmessage = function(e){
output("got response: " + e.data);
}
function closeSocket(){
websocket.close();
}
websocket.onclose = function(){
output("disconnected");
}
function output(t){
document.getElementById("output").innerHTML += t + "<br />";
}
C# Server:
using System;
using System.Net;
using System.Net.Sockets;
namespace WebSocketsTutorial {
class Program {
static void Main(string[] args) {
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
TcpClient client = default(TcpClient);
server.Start();
Console.WriteLine("server started");
while (true) {
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
foreach (byte b in receivedBuffer) {
Console.Write(Convert.ToChar(b).ToString());
}
}
}
}
}
This is what is output on the console when the client connects:
What I'm mainly looking to do is to allow an arbitrary number of connections and ultimately have the server echo a user's submission to all connected clients.
↧