0

我正在寻找一种在 android 和 C# 2012 之间通过 TCP 或 HTTP 进行通信的方法。这是我到目前为止所拥有的

JAVA客户端:

package com.example.test;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView tc;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btn = (Button)this.findViewById(R.id.button1);
        tc = (TextView) this.findViewById(R.id.textView1);
        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                Thread th = new Thread(new Runnable() {

                    public void run() {
                        connect();
                    }

                });
                th.start();
            }

        });


    }


    private void connect() {

        InetAddress[] server;
        try {
            server = InetAddress.getAllByName("192.168.1.100");

            Socket socket = new Socket(server[0], 3975);

            if (socket.isConnected()){
                Log.d("connected", "connected");
            }

            PrintWriter w = null;
            BufferedReader r = null;

            w = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
            r = new BufferedReader(new InputStreamReader(socket.getInputStream()));                

            w.println("test");
            /*String m = null;

            while ((m=r.readLine())!= null) {
                w.write(m,0,m.length());
                w.flush();
             }*/



        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("error", e.getMessage());
        }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

C# 服务器:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{

}

public async void ServiceButtonClick(object sender, RoutedEventArgs e)
{



    StreamSocketListener listener = new StreamSocketListener();
    listener.ConnectionReceived += OnConnection;

    try
    {
        await listener.BindServiceNameAsync("3975");
        lblMessage.Text = "We are listening for connections...";
    }
    catch (Exception ee)
    {
        lblMessage.Text = "Unable to bind service.. " + ee.Message;
    }
}

private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{

    DataReader reader = new DataReader(args.Socket.InputStream);


    this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        lblMessage.Text = "We are connected to the client";
    });


    try
    {
        while (true)
        {
            uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
            if (sizeFieldCount != sizeof(uint))
            {
                this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 1";
                });
                return;
            }
            uint stringLength = reader.ReadUInt32();
            uint actualStringLength = await reader.LoadAsync(stringlength);
            if (stringLength != actualStringLength)
            {
                this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                {
                    lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 2";
                });
                return;
            }

            string temp;
            temp = reader.ReadString(actualStringLength);

            this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                lblMessage.Text = "Client said - " + reader.ReadString(3);
            });

        }

    }
    catch (Exception e)
    {
        this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
        {
            lblMessage.Text = "ERROR: " + e.Message + " - " + e.Source + " - " + e.StackTrace;
        });
    }


}

}

现在,当我单击客户端上的按钮时,套接字已连接,但是当我从手机向 C# 服务器发送数据时,服务器上没有显示任何内容。我在接收端或发送端做错了什么吗?我只是想通过 TCP 发送基本字符串。

4

0 回答 0