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

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

问题描述

我对C#在Android客户端和服务器。客户端发送信息到服务器,它的罚款。但我需要服务器发送文件夹和文件的要求列表中指定的目录,不知道该怎么做,因为客户端没有得到任何消息,从服务器。的code,它是为了听不工作,应用程序只需stucks,直到我关闭服务器应用程序的客户端的一部分,那么它的作品了,但仍然不读什么。 在此先感谢

客户端:

 包com.app.client.app;

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

进口java.io.BufferedReader中;
进口java.io.BufferedWriter中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStreamWriter中;
进口java.io.InputStreamReader中;
进口的java.io.PrintWriter;
进口的java.net.InetAddress;
进口的java.net.Socket;
进口的java.net.UnknownHostException;

进口android.util.Log;

公共类my_activity延伸活动{
私人TextView的TXT;

@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    按钮B =(按钮)findViewById(R.id.button1);
    TXT =(TextView中)findViewById(R.id.textView1);


    b.setOnClickListener(新View.OnClickListener(){

        @覆盖
        公共无效的onClick(视图v){
            // TODO自动生成方法存根
        connectSocket(你好);

        }
    });
}

私人无效connectSocket(字符串一){

    尝试 {
        InetAddress类serverAddr = InetAddress.getByName(192.168.1.2);
        Log.d(TCP,C:连接...);
        Socket套接字=新的Socket(serverAddr,4444);

        信息=1;

        PrintWriter的输出= NULL;
        BufferedReader中的= NULL;

        尝试 {
            Log.d(TCP,C:发送:+信息+');
            OUT =的新PrintWriter(新的BufferedWriter(新OutputStreamWriter(socket.getOutputStream())),TRUE);
            在=新的BufferedReader(新的InputStreamReader(socket.getInputStream()));

            通过out.println(消息);
            而((in.readLine())!= NULL){
                txt.append(in.readLine());
            }

            Log.d(TCP,C:发送。);
            Log.d(TCP,C:完成。);

        }赶上(例外五){
            Log.e(TCP,S:错误,E);
        } 最后 {
            socket.close();
        }

    }赶上(UnknownHostException异常E){
        // TODO自动生成的catch块
        Log.e(TCP,C:UnknownHostException异常,E);
        e.printStackTrace();
    }赶上(IOException异常E){
        // TODO自动生成的catch块
        Log.e(TCP,C:IO​​Exception异常,E);
        e.printStackTrace();
    }
}
}
 

服务器:

 使用系统;
使用System.Text;
使用System.Collections.Generic;
使用System.Linq的;
使用System.Net;
使用的System.Net.Sockets;
使用System.Windows.Forms的;

公共类SERV {
    公共静态无效的主要(){
    尝试 {
    ip地址的iPad = IPAddress.Parse(192.168.1.2);
     //使用本地M / C的IP地址,

     //在客户端使用相同的


/ *初始化监听* /
    的TcpListener myList上=新的TcpListener(iPad版,4444);

/ *开始Listeneting在指定的端口* /
    myList.Start();

    Console.WriteLine(服务器在端口4444上运行......);
    Console.WriteLine(当地的终点是:+
                      myList.LocalEndpoint);
    Console.WriteLine(正在等待连接......);
    M:
    插座S = myList.AcceptSocket();
    Console.WriteLine(连线接受了+ s.RemoteEndPoint);

    byte []的B =新的字节[100];
    INT K = s.Receive(B);

    焦炭CC ='';
    字符串测试= NULL;
    Console.WriteLine(:收到......);
    的for(int i = 0; I< K-1;我++)
    {
        Console.Write(Convert.ToChar(B [i]));
        CC = Convert.ToChar(二[I]);
        测试+ = cc.ToString();
    }

    开关(试验)
    {
        情况1:
            打破;


    }

    ASCIIEncoding ASEN =新ASCIIEncoding();
    s.Send(asen.GetBytes(该字符串:收到的服务器。));
    Console.WriteLine(\ nSent确认);


/* 清理 */
    转到米;
    S.CLOSE();
    myList.Stop();
    到Console.ReadLine();

}
赶上(例外五){
    Console.WriteLine(错误.....+ e.StackTrace);
}
}

}
 

解决方案

好吧,我找到了解决你的问题。

在你的C#的服务器,您发送的文字:

  ASCIIEncoding日月=新ASCIIEncoding();
s.Send(asen.GetBytes(该字符串:收到的服务器。));
S.CLOSE();
 

确认此处关闭套接字一旦你发送的数据。这就是为什么你的应用程序将挂起。它正在等待更多的投入从服务器

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

 字符串文本=;
字符串finalText =;
而((文= in.readLine())!= NULL){
    finalText + =文本;
    }
txt.setText(finalText);
 

请注意你正在做2 readInputs在这个循环。 while语句做一件..并设置文本做的..所以你基本上是试图在一个循环读取2行。改变什么,我上面贴将解决这个问题

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

Client:

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(); 
    }       
} 
} 

Server:

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("\nSent 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.

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();

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

Also, change to this in Java where you receive

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

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天全站免登陆