HTML + javascript(js) tcp client & c# tcp server example

HTML + javascript(js) tcp client & c# tcp server example

HTML + javascript(js) tcp client & c# tcp server example


資料來源: 01.Copilot

02.https://github.com/jash-git/CS_TCP_project [C# SERVER]

03.https://github.com/jash-git/CS_test_jint-project [JS 產生 熱敏打印機 _ESC 指令/ 標籤機(TSC)指令]


HTML+JS code [傳送字串]

<!DOCTYPE html>
<html>
<head>
    <title>TCP Client</title>
</head>
<body>
    <h1>TCP Client</h1>
    <button onclick="sendMessage()">Send Message</button>

    <script>
        function sendMessage() {
            const socket = new WebSocket('ws://192.168.1.106:8888');
            socket.onopen = function(event) {
                socket.send('Hello, Server!');
            };
            socket.onmessage = function(event) {
                console.log('Message from server: ' + event.data);
            };
        }
    </script>
</body>
</html>


HTML+JS code [HEX 字串] 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Hex Array</title>
</head>
<body>
    <script>
        // Create a WebSocket connection
        const socket = new WebSocket('ws://localhost:8888');

        socket.onopen = () => {
            console.log('WebSocket connection opened');

            // Create a hex array
            const hexArray = [0x0F, 0x1A, 0x2B, 0x3C];
            const buffer = new Uint8Array(hexArray);

            // Send the hex array
            socket.send(buffer);
            console.log('Hex array sent');
        };

        socket.onmessage = (event) => {
            console.log('Received:', event.data);
        };

        socket.onclose = () => {
            console.log('WebSocket connection closed');
        };
    </script>
</body>
</html>


==================


C# code

using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;

namespace csharp_multi_threaded_server_socket
{
    //資料來源 http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener serverSocket = new TcpListener(8888);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;

            serverSocket.Start();
            Console.WriteLine(" >> " + "Server Started");

            counter = 0;

            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();
                Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
                handleClinet client = new handleClinet();
                client.startClient(clientSocket, Convert.ToString(counter));
            }

            clientSocket.Close();
            serverSocket.Stop();
            Console.WriteLine(" >> " + "exit");
            Console.ReadLine();
        }
    }

    //Class to handle each client request separatly
    public class handleClinet
    {
        TcpClient clientSocket;
        string clNo;
        public void startClient(TcpClient inClientSocket, string clineNo)
        {
            this.clientSocket = inClientSocket;
            this.clNo = clineNo;
            Thread ctThread = new Thread(doChat);
            ctThread.Start();
        }

        private void doChat()
        {
            int requestCount = 0;
            byte[] bytesFrom = new byte[10025];
            string dataFromClient = null;
            Byte[] sendBytes = null;
            string serverResponse = null;
            string rCount = null;
            requestCount = 0;

            while ((true))
            {
                try
                {
                    requestCount = requestCount + 1;
                    NetworkStream networkStream = clientSocket.GetStream();
                    networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);

                    rCount = Convert.ToString(requestCount);
                    serverResponse = "Server to clinet(" + clNo + ") " + rCount;
                    sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
                }
                catch (Exception ex)
                {
                    clientSocket.Close();
                    Console.WriteLine(" >> " + "Server to clinet(" + clNo + ") closed..." );
                    break;
                }
            }
        }

    }
}

3 thoughts on “HTML + javascript(js) tcp client & c# tcp server example

  1. JS 只能單純使用 WebSocket 它和 Node.js 的純Socket 差別就在於 WebSocket 傳送資料 要有Head 所以並非單純TCP連線

    1. 所以要拿JS 的 WebSocket 來時做控制應用 必須在架設一個WebSocket Server 來分析 它的封包

      建議使用ESP32 來做一個中介層 實現 硬體翻譯封包功能

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *