Client Server tcp app不稳定 [英] Client Server tcp app not stable

查看:94
本文介绍了Client Server tcp app不稳定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建这样的应用程序:



用户在客户端选择日期。

当他点击发送按钮时客户端发送日期通过TCP到服务器。

当服务器收到日期时,他处理它们并以字符串形式返回客户端csv。

当客户收到时,他将数据写入文件。



继承人我的代码:



服务器部分:



I wanted to create apps like this:

User select dates in client up.
When he clicks send button client sends dates over TCP to server.
When server receives dates he process them and retuns to client csv in string.
When client receives he writes data to file.

Heres my code:

Servers part:

private void StartListen()
{
    server.Start(); // Starts Listening to Any IPAddress trying to connect to the program with port 1980
    new Thread(() => // Creates a New Thread (like a timer)
    {
        client = server.AcceptTcpClient(); //Waits for the Client To Connect
        zapisiLog("klient se spojio");
        if(client.Connected) // If you are connected
        {
            ServerReceive(); //Start Receiving
        }
    }).Start();
}
public void ServerReceive()
{
    stream = client.GetStream(); //Gets The Stream of The Connection
    new Thread(() => // Thread (like Timer)
    {
        while((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
        {
            byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
            stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
            this.Invoke((MethodInvoker) delegate // To Write the Received data
            {
                String s = Encoding.Default.GetString(data); // Converts Bytes Received to String
                string[] datumi = s.Split('_');
                sd1 = datumi[0];
                sd2 = datumi[1];
                mstat = datumi[2];
//this is a funtion that coonects to database and return tables
                DataSet dset = prikupi_podatke();

                if(datumi[2] != "" & dset != null)
                {
                    String zs = obradi(ref dset);
                    if(zs != "")
                    {
                        ServerSend(zs);
                    }
                    else
                    {
                        zapisiLog("Obrada podataka nije uspjela");
                    }
                }
                else
                {
                    zapisiLog("Prikupljanje podataka nije uspjelo");
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\codexExcel.log");
                    try
                    {

                        sw.WriteLine(DateTime.Now.ToString() + ";Prikupljanje podataka nije uspjelo");
                        sw.Close();
                    }
                    catch(Exception)
                    {
                        sw.Close();
                    }
                }
            });
        }
    }).Start(); // Start the Thread
}





客户端部分:



Clients part:

public void spoji()
{
    try
    {
        client = new TcpClient(ip, 1980); //Trys to Connect
        ClientReceive(); //Starts Receiving When Connected
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message); // Error handler :D
    }
}
public void ClientSend(string msg)
{
    stream = client.GetStream(); //Gets The Stream of The Connection
    byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
    data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
    int length = data.Length; // Gets the length of the byte data
    byte[] datalength = new byte[4]; // Creates a new byte with length of 4
    datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
    stream.Write(datalength, 0, 4); // sends the data's length
    stream.Write(data, 0, data.Length); //Sends the real data
}
public void ClientReceive()
{
    string primljeno;
    stream = client.GetStream(); //Gets The Stream of The Connection
    new Thread(() => // Thread (like Timer)
    {
        while((i = stream.Read(datalength, 0, 4)) != 0)//Keeps Trying to Receive the Size of the Message or Data
        {
            // how to make a byte E.X byte[] examlpe = new byte[the size of the byte here] , i used BitConverter.ToInt32(datalength,0) cuz i received the length of the data in byte called datalength :D
            byte[] data = new byte[BitConverter.ToInt32(datalength, 0)]; // Creates a Byte for the data to be Received On
            stream.Read(data, 0, data.Length); //Receives The Real Data not the Size
            this.Invoke((MethodInvoker) delegate // To Write the Received data
            {
                primljeno = Encoding.UTF8.GetString(data); // Encoding.Default.GetString(data); Converts Bytes Received to String
                if(primljeno != "")
                {
                    //klijent pbrađuje
                    //obradi(ref primljeno);
                    //server obrađuje
                    obradi2(ref primljeno);
                }
                else
                {
                    MessageBox.Show("Komunikacija nije uspjela");
                }

            });
        }
    }).Start(); // Start the Thread
}



当服务器和主机在同一台机器上时,应用程序运行良好。但在不同的机器上不稳定。由于工作不正常,我的意思是应用程序崩溃,服务器没有响应。我做错了什么?


Applications are working well when server and host are on same machine. But not stable on different machines. By not working well I mean app crash with "server is not responding". What am i doing wrong?

推荐答案

我不建议您在代码中使用它们的方式使用线程,而是在MSDN上查看这些示例:< br $> b $ b

异步客户端套接字示例 [ ^ ]

异步服务器套接字示例 [ ^ ]



基于这些示例我在不同的机器上运行了一些应用程序,并且没有任何严重的问题。

我必须补充一点,我一直在内部网络上使用这个概念,其中服务器一次处理10-15个客户端并且请求加载非常低。
I would not recommend using threads the way you are using them in your code, instead take a look at these examples on MSDN:

Asynchronous Client Socket Example[^]
Asynchronous Server Socket Example[^]

I have based some applications running on different machines on these examples and haven't had any serious issues.
I have to add that I have been using this concept on an internal network where the server took care of maybe 10-15 clients at a time and the request load was pretty low.


这篇关于Client Server tcp app不稳定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆