如何实现接受更多消息的套接字服务器

时间:2018-07-27 15:48:15

标签: c# android sockets

我想将一些数据从Android应用程序实时发送到服务器。

因此,我正在c#中构建一个简单的套接字服务器,如下所示:

class Program
    {
        private Socket listener;
        static void Main(string[] args)
        {
            Program p = new Program();
            p.socketServer();
        }

        public void socketServer()
        {
            int MAXBUFFER = 1024;
            Console.WriteLine("SOCKET STARTED");
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(IPAddress.Any, 8080));
            listener.Listen(10);
            while (true)
            {
                Console.WriteLine("WAITING CONNECTION");
                Socket socket = listener.Accept();
                string receivedMessage = string.Empty;
                while (true)
                {
                    byte[] receivedBytes = new byte[MAXBUFFER];
                    int numBytes = socket.Receive(receivedBytes);
                    receivedMessage += Encoding.ASCII.GetString(receivedBytes, 0, numBytes);
                    if (receivedMessage.IndexOf("\n") > -1)
                    {
                        Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
                        //break;
                    }
                }
                Console.WriteLine("MESSAGE FROM CLIENT: {0}", receivedMessage);
                string replyMessage = "MESSAGE RECEIVED";
                byte[] replyBytes = Encoding.ASCII.GetBytes(replyMessage);

            }
        }

        public void shutdownServer()
        {
            listener.Shutdown(SocketShutdown.Both);
            listener.Close();
        }
    }

我正在构建此类以从A​​ndroid应用程序发送数据:

public class TcpClient {

    public static final String SERVER_IP = "192.168.110.50"; // computer IP address
    public static final int SERVER_PORT = 8080;

    private String mServerMessage;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;
    private PrintWriter mBufferOut;
    private BufferedReader mBufferIn;
    private Socket socket;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TcpClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     *
     * @param message text entered by client
     */
    public void sendMessage(String message) {
        socket.isConnected();
        if (mBufferOut != null /*&& !mBufferOut.checkError()*/) {
            mBufferOut.println(message);
        }
    }

    /**
     * Close the connection and release the members
     */
    public void stopClient() {
        Log.i("Debug", "stopClient");

        // send mesage that we are closing the connection
        //sendMessage(Constants.CLOSED_CONNECTION + "Kazy");

        mRun = false;

        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }

        mMessageListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
        //create a socket to make the connection with the server
            socket = new Socket(SERVER_IP, SERVER_PORT);
            //socket.connect(socket.getRemoteSocketAddress());
            socket.isConnected();
            try {
                Log.i("Debug", "inside try catch");

                mBufferOut = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),
                        true);

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {

            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

     public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

在MainActivity中,我使用以下代码:

tcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
                        @Override
                        //here the messageReceived method is implemented
                        public void messageReceived(String message) {

                            //this method calls the onProgressUpdate
                            //publishProgress(message);

                        }
                    });
                    tcpClient.run();

连接到服务器后,我使用此代码发送消息:

for(int i=0; i<10; i++){
    tcpClient.sendMessage("test " + i);
}

问题在于只有第一条消息到达服务器。我认为问题出在与客户端失去连接的套接字服务器上。

0 个答案:

没有答案