简体   繁体   English

我如何做一个线程客户端套接字

[英]How can I do a threaded Client socket

I've done a simple ASPX page with just one <asp:Button> . 我用一个<asp:Button>完成了一个简单的ASPX页面。 This page will do a connection with a Windows Form application via Socket. 该页面将通过套接字与Windows Form应用程序建立连接。

How Should Work 应该如何工作

Everytime that I click in my <asp:Button> I have to pass some information to my Windows Form read, and then I will print it. 每次单击<asp:Button>我都必须将一些信息传递给Windows窗体读取的内容,然后将其打印出来。

TCP Server Code TCP服务器代码

public partial class PaginaTeste : System.Web.UI.Page
{
    private TcpListener tcpListener;
    private Thread listenThread;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnBotao_OnClick(object sender, EventArgs e)
    {
        this.tcpListener = new TcpListener(IPAddress.Any, 8849);
        this.listenThread = new Thread(new ThreadStart(ListenForClients));
        this.listenThread.Start();
    }

    private void ListenForClients()
    {
        this.tcpListener.Start();

        while (true)
        {
            //blocks until a client has connected to the server
            TcpClient client = this.tcpListener.AcceptTcpClient();

            //create a thread to handle communication 
            //with connected client
            Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            clientThread.Start(client);
        }
    }

    private void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                string serverResponse = "571764;10.";                        
                Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                clientStream.Write(sendBytes, 0, sendBytes.Length);
                clientStream.Flush();
            }
            catch
            {
                //a socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                //the client has disconnected from the server
                break;
            }
        }

        tcpClient.Close();
    }

Client Code (Windows Form) 客户端代码(Windows窗体)

   public partial class Form1 : Form
    {
        TcpClient clientsocket2;
        Thread thread;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {         
        }

        private void button3_click(object sender, EventArgs e)
        {
            this.clientsocket2 = new TcpClient();
           clientsocket2.Connect("server_ip", 8849);       
            this.thread = new Thread(new ThreadStart(this.imprimir));
            this.thread.Start();
        }
protected void imprimir()
        {       
            NetworkStream serverStream = clientsocket2.GetStream();
            byte[] inStream = new byte[10025];
            serverStream.Read(inStream, 0, (int)clientsocket2.ReceiveBufferSize);
            string returndata = System.Text.Encoding.ASCII.GetString(inStream);

            string r = "Printing Test";
            int retorno = -1;

            retorno = IniciaPorta("COM7");            

            if (retorno == 1)
            {
                ConfiguraModeloImpressora(7);
                BematechTX(r);
                AcionaGuilhotina(1);
                FechaPorta();
            }

            clientSocket.Close();
        }

Problem 问题

If I click once in my <asp:Button> and initiallize my Client Application works fine. 如果我在<asp:Button>单击一次并初始化,则我的Client Application正常运行。 In the second time that I click in my <asp:Button> the parameter that I pass to my Client Application return empty. 在第二次单击<asp:Button> ,传递给Client Application的参数返回空。

Where I read empty in my client application 在客户应用程序中我读为空的地方

string returndata = System.Text.Encoding.ASCII.GetString(inStream);

Why you create tcpListener when press button in your page? 为什么在页面中按按钮时创建tcpListener? You need create TcpClient and send comand to you Winform App This code send comand and get reply from server 您需要创建TcpClient并将comand发送给您Winform App这段代码发送comand并从服务器获取回复

string data = "Some_Comand";
        byte[] b = Encoding.ASCII.GetBytes(data);
        byte[] buffer = new byte[1024];
        var client = new TcpClient();
        var serverEndPoint = new IPEndPoint(IPAddress.Parse("ip"), 8010);
        client.Connect(serverEndPoint);
        var clientStream = client.GetStream();
        clientStream.Write(b, 0, b.Length);
        Socket s = client.Client;
        byte[] receiveData = new byte[200];
        s.Receive(receiveData);
        Debug.WriteLine(Encoding.ASCII.GetString(receiveData));

Thats all 就这样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 C# 通过套接字向客户端发送 cookie? - How do I send cookies to the client via a socket with C#? 如何确保覆盖线程代码 - How can I ensure coverage of threaded code 如何确保在多线程环境中对StringBuilder对象进行GC? (鉴于我不能使用using关键字)? - How do I ensure that the StringBuilder object is GCed in a multi-threaded environment? (Given that I can't use the using Keyword)? 如何检测多线程使用? - How do I detect multi-threaded use? 如何将套接字作为参数传递给ButtonClick处理函数? - How can I pass socket as an argument do ButtonClick handler function? 如何创建自定义SynchronizationContext,以便我自己的单线程事件循环可以处理所有延续? - How do I create a custom SynchronizationContext so that all continuations can be processed by my own single-threaded event loop? 如何在C#中控制线程窗口 - How can I control threaded windows in C# 如何避免线程化应用程序中的全局变量 - How can I avoid global variables in a Threaded application 如何在Threaded .Net Web服务中启用会话? - How can I enable session in Threaded .Net Webservice? 我如何使用WCF服务而不是套接字客户端服务器应用程序? - how do i use WCF service instead of socket client-server application?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM