发送时服务器仍然挂 [英] Server remains hang when sending

查看:149
本文介绍了发送时服务器仍然挂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我书面方式在客户端(Android版) - 服务器(C#)应用程序。我得到的code从这里:
<一href=\"http://stackoverflow.com/questions/6387579/how-to-make-client-on-android-listen-to-server-on-c\">How使客户端在Android上听取他们对C#服务器?
万物工作正常,当我刚刚从客户端发送消息到服务器,从服务器到客户端(关闭服务器端的插座)。现在,我想的是:发送消息到服务器,从服务器中接收消息,然后再一个消息发送到服务器。服务器挂起,在发送邮件。如果我发送后关闭服务器端插座,它给出了一个错误处置,我可以从服务器发送的数据。

I'm writting a client(Android) - server(c#) application. I get the code from here: How to make client on Android listen to server on C#? Everythings is working fine, when i just send message from the client to server, and from server to client (closing the socket on server side). Now, what i want is : send message to server, receive message from server, then send again a message to server. The server hangs at sending the message. If i close the socket on server side after sending, it gives a dispose error, and i can's send the data from the server.

我的服务器code是:

My server code is:

/*************************************SERVER*****************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace SERVER2
{
    class Program
    {
        public static void Main()
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("192.168.2.102");

                TcpListener myList = new TcpListener(ipAd, 18001);

                myList.Start();

                Console.WriteLine("The server is running at port 18001...");
                Console.WriteLine("The local End point is  :" +
                                  myList.LocalEndpoint);
                Console.WriteLine("Waiting for a connection.....");
                 m:
                Socket s = myList.AcceptSocket();
                Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                byte[] b = new byte[100];
                int k = s.Receive(b);

                char cc = ' ';
                string test = null;
                Console.WriteLine("Recieved1...");
                for (int i = 0; i < k - 1; i++)
                {
                    cc = Convert.ToChar(b[i]);
                    test += cc.ToString();
                }
                Console.WriteLine("Received characters1: "+test);

                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes("The string was recieved by the server."));
                Console.WriteLine("\nSent Acknowledgement");
                //s.Close(); <-if i enable this, i get a dispose error

                k = s.Receive(b);//i get dispose error here

                cc = ' ';
                test = null;
                Console.WriteLine("Recieved2...");
                for (int i = 0; i < k - 1; i++)
                {
                    cc = Convert.ToChar(b[i]);
                    test += cc.ToString();
                }
                Console.WriteLine("Received characters2: " + test);

                /* clean up */
                goto m;
                s.Close();
                myList.Stop();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.Message);
            }
            Console.ReadLine();
        }

    }
}

我的客户code是:

My client code is:

/******************************CLIENT*****************************************/
    Socket socket = null;
        try 
        {
            Toast.makeText(context,"IP: "+ip+" port: "+port,10000).show();
            InetAddress serverAddr = InetAddress.getByName(ip); 
            socket = new Socket(serverAddr, port);
        } 
        catch (UnknownHostException e1) 
        {
            Toast.makeText(context,"UnknownHostException ",10000).show();
        } 
        catch (IOException e1) 
        {
            Toast.makeText(context,"IOException ",10000).show();
        }

        String message = "1";

        PrintWriter out = null;
        BufferedReader in = null;

        try { 
            Log.d("TCP", "C: Sending: '" + message + "'"); 

            /*write*/
            out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
            out.println(message);
            out.flush();
            /*read*/
            in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
            String text = "";
            String finalText = "";
            while ((text = in.readLine()) != null) 
            {
                finalText += text;
                }
            Toast.makeText(context, "FinalText: "+finalText, 10000).show();
            Log.d("TCP", "C: Sent.");
            Log.d("TCP", "C: Done."); 
            in.close();        

            /*write*/
            out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
            out.println(message);
            out.flush();
        } catch(Exception e) { 
            Log.e("TCP", "S: Error", e); 
        } finally { 
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 

感谢先进的!

推荐答案

的问题是,当客户端收到的消息,从服务器中,而部分进入一个无限循环。我修改我的应用程序是这样的:

The problem was that when the client received the message from the server , in the while part entered into an infinite loop. I modify my app like this:

我的客户端部分:

try 
        {
            Toast.makeText(context,"IP: "+ip+" port: "+port,10000).show();
            InetAddress serverAddr = InetAddress.getByName(ip); 
            socket = new Socket(serverAddr, port);
        } 
        catch (UnknownHostException e1) 
        {
            Toast.makeText(context,"UnknownHostException ",10000).show();
        } 
        catch (IOException e1) 
        {
            Toast.makeText(context,"IOException ",10000).show();
        }

        String message = "HELLO FROM CLIENT";

        PrintWriter out = null;
        BufferedReader in = null;

        try { 
            Log.d("TCP", "C: Sending: '" + message + "'"); 

            /*write*/
            OutputStream ostr=socket.getOutputStream();
            OutputStreamWriter outputstr=new OutputStreamWriter(ostr);
            BufferedWriter buffw=new BufferedWriter(outputstr);
            out = new PrintWriter(buffw ,true);
            out.println("HELLO 1 FROM CLIENT");

            /*read - i modify to this*/
            InputStreamReader reader=new InputStreamReader(socket.getInputStream());
            char[] bytesreceived=new char[50];
            reader.read(bytesreceived    , 0, 50);
            String text="";
            for (int i=0;i<bytesreceived.length;i++)
            {
                text+=bytesreceived[i];
            }
            Toast.makeText(context, "Received1: "+text.trim(), 10000).show();
            Log.d("IdealLog","Received1: "+text.trim());

            /*write*/
            out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
            out.println("HELLO 2 FROM CLIENT");

            /*read*/
            reader=new InputStreamReader(socket.getInputStream());
            bytesreceived=new char[50];
            reader.read(bytesreceived    , 0, 50);
            text="";
            for (int i=0;i<bytesreceived.length;i++)
            {
                text+=bytesreceived[i];
            }
            Toast.makeText(context, "Received2: "+text.trim(), 10000).show();
            Log.d("IdealLog","Received2: "+text.trim());

        } catch(Exception e) { 
            Log.e("TCP", "S: Error", e); 
        } finally { 
            try {
                socket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 

我的服务器端code:

My server side code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 18001);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            socket.Bind(ip);
            socket.Listen(10);
            Console.WriteLine("Waiting for a client...");
            Socket client = socket.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);



            string welcome = "HELLO 1 FROM SERVER";
            byte[] data = new byte[200];
            int receiveddata=client.Receive(data);
            Console.WriteLine("Received data from CLIENT1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data).Trim());



            ASCIIEncoding asen = new ASCIIEncoding();
            byte[] data2 = new byte[200];
            data2 = asen.GetBytes(welcome);
            int sentdata=client.Send(data2, data2.Length, SocketFlags.None);
            Console.WriteLine("Sent data from SERVER: {0}", welcome);



            byte[] data3 = new byte[200];
            Console.WriteLine("Receiving data from CLIENT : {0}", "...");
            client.Receive(data3);


            Console.WriteLine("Received data from CLIENT2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3).Trim());
            byte[] data4 = new byte[200];
            data4 = asen.GetBytes("HELLO 2 FROM SERVER");
            sentdata = client.Send(data4, data4.Length, SocketFlags.None);

            client.Close();
            socket.Close();


            Console.WriteLine("Disconnected from {0}", clientep.Address);



            Console.ReadLine();
        }
    }
}

现在,一切工作正常,没有窍门。唯一的问题是,我不知道这是否会接收,发送文件。

Now, everything is working fine, without hang. The only problem is, that i don't know if this will work for receiving , sending files.

这篇关于发送时服务器仍然挂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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