如何让 Android 上的客户端在 C# 上收听服务器? [英] How to make client on Android listen to server on C#?

查看:17
本文介绍了如何让 Android 上的客户端在 C# 上收听服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Android 上有一个客户端,在 c# 上有一个服务器.客户端向服务器发送消息,这很好.但是我需要服务器根据请求发送指定目录中的文件夹和文件列表,但不知道该怎么做,因为客户端没有从服务器收到任何消息.用于侦听的客户端代码部分不起作用,应用程序只是卡住,直到我关闭服务器应用程序,然后它再次工作,但仍然没有读取任何内容.提前致谢

I have a client on Android and server on c#. The client sends messages to server and it's fine. But I need server to send on request list of folders and files in specified directory and don't know how to do that, because client doesn't get any messages from server. The client's part of code that is intended to listen doesn't work, the application simply stucks until I close the server application, then it works again, but still doesn't read anything. Thanks in advance

客户:

package com.app.client.app;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream;
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader;
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 

import android.util.Log; 

public class my_activity extends Activity { 
private TextView txt;

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Button b = (Button)findViewById(R.id.button1);
    txt = (TextView)findViewById(R.id.textView1);


    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        connectSocket("Hello");

        }
    });
} 

private void connectSocket(String a){ 

    try { 
        InetAddress serverAddr = InetAddress.getByName("192.168.1.2"); 
        Log.d("TCP", "C: Connecting..."); 
        Socket socket = new Socket(serverAddr, 4444); 

        message = "1";

        PrintWriter out = null;
        BufferedReader in = null;

        try { 
            Log.d("TCP", "C: Sending: '" + message + "'"); 
            out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                

            out.println(message);
            while ((in.readLine()) != null) {
                txt.append(in.readLine());
            }

            Log.d("TCP", "C: Sent."); 
            Log.d("TCP", "C: Done.");               

        } catch(Exception e) { 
            Log.e("TCP", "S: Error", e); 
        } finally { 
            socket.close(); 
        } 

    } catch (UnknownHostException e) { 
        // TODO Auto-generated catch block 
        Log.e("TCP", "C: UnknownHostException", e); 
        e.printStackTrace(); 
    } catch (IOException e) { 
        // TODO Auto-generated catch block 
        Log.e("TCP", "C: IOException", e); 
        e.printStackTrace(); 
    }       
} 
} 

服务器:

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

public class serv {
    public static void Main() {
    try {
    IPAddress ipAd = IPAddress.Parse("192.168.1.2");
     // use local m/c IP address, and 

     // use the same in the client


/* Initializes the Listener */
    TcpListener myList=new TcpListener(ipAd,4444);

/* Start Listeneting at the specified port */        
    myList.Start();

    Console.WriteLine("The server is running at port 4444...");    
    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("Recieved...");
    for (int i = 0; i < k-1; i++)
    {
        Console.Write(Convert.ToChar(b[i]));
        cc = Convert.ToChar(b[i]);
        test += cc.ToString();
    }

    switch (test)
    {
        case "1":                 
            break;


    }

    ASCIIEncoding asen=new ASCIIEncoding();
    s.Send(asen.GetBytes("The string was recieved by the server."));
    Console.WriteLine("
Sent Acknowledgement");


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

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

}

推荐答案

好的,我找到了解决您问题的方法.

Ok, I found the solution to your problem.

在您发送文本的 c# 服务器中:

In your c# server where you send the text:

ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
s.Close();

确保在发送数据后关闭此处的套接字.这就是您的应用程序会挂起的原因.IT 正在等待来自服务器的更多输入

Make sure to close the socket here once you send the data. thats why your app would hang. IT was waiting for more input from the server

另外,在您收到的 Java 中更改为这个

Also, change to this in Java where you receive

String text = "";
String finalText = "";
while ((text = in.readLine()) != null) {
    finalText += text;
    }
txt.setText(finalText);

注意你是如何在该循环中执行 2 个 readInputs 的.while 语句执行一个.. 而设置文本执行一个.. 所以您实际上是在一个循环中尝试读取 2 行.更改为我上面发布的内容将解决此问题

Notice how you're doing 2 readInputs in that loop. The while statement does one.. and setting the text does one.. so you're essentially trying to read 2 lines during one loop. Changing to what i posted above will fix that

这篇关于如何让 Android 上的客户端在 C# 上收听服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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