简单的异步android客户端与简单的c#服务器

时间:2013-10-19 11:00:19

标签: c# android

我已经实现了一个非常基本的客户端(android,扩展asyncTask)和服务器(C#)。这是我第一次使用android(java)网络编程,但我已经在C#/ C ++中实现了许多客户端/服务器应用程序包括实时视频流(C#)。 问题:一切都很顺利,但我的android客户端每次都收到相同的数据。 那是“[B @ 43b9f600”。以下是我的客户端和服务器代码。

package com.example.tcpasyncclientbullshittest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    String SERVER_IP="192.168.1.3";
    Integer SERVER_PORT = 7878;

    Button connect,start,send;
    EditText smsg,rmsg;

    Socket socket;

    InputStream in;
    OutputStream out;

    byte[] buffer;


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

        connect = (Button) findViewById(R.id.connect);
        start = (Button) findViewById(R.id.start);
        send  = (Button) findViewById(R.id.send);

        smsg = (EditText) findViewById(R.id.smsg);
        rmsg = (EditText) findViewById(R.id.rmsg);

        buffer = new byte[100];

        socket = new Socket();

        connect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                SocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVER_PORT);
                try {
                    socket.connect(socketAddress);
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_SHORT).show();
                }
            }
        });

        class MyParallelReceiver extends AsyncTask<Void, String, Void>{
            @Override
            protected Void doInBackground(Void... params) {
                // TODO Auto-generated method stub
                while(true){
                    try {
                        in = socket.getInputStream();
                        int bytesReceived = in.read(buffer);
                        if(bytesReceived > 0){
                            publishProgress("He");
                            String data = null;
                            data = buffer.toString();
                            publishProgress(data);
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            @Override
            protected void onProgressUpdate(String... values) {
                // TODO Auto-generated method stub
                //super.onProgressUpdate(values);
                if(values[0] == "He"){
                    Toast.makeText(getApplicationContext(), "Recvd", Toast.LENGTH_LONG).show();
                }
                else{
                    rmsg.append(values[0].toString()+";");
                    Toast.makeText(getApplicationContext(), values[0].toString(), Toast.LENGTH_LONG).show();
                }

            }
        }

        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new MyParallelReceiver().execute(new Void[1]);              
            }
        });


        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String sdata = null;
                sdata = smsg.getText().toString();
                if(sdata != null){
                    try {
                        Toast.makeText(getApplicationContext(), "Sending...", Toast.LENGTH_SHORT).show();
                        out = socket.getOutputStream();
                        out.write(sdata.getBytes());
                        Toast.makeText(getApplicationContext(), "Sent", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }               
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

和c#server:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AndroidTCP_TryTest
{
     public partial class Form1 : Form
     {
          const int SERVER_PORT = 7878;
          Socket server;
          Socket client;
          byte[] buffer;
          IPEndPoint client_address;
          Thread receiver;

          public Form1()
          {
               InitializeComponent();
               server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               receiver = new Thread(new ThreadStart(Receive));
          }

          private void Receive() 
          {
               while (true)
               {
                    try
                    {
                         buffer = new byte[100];
                         int nobs = client.Receive(buffer);
                         if (nobs>0)
                         {
                              lock (richTextBoxReceived)
                              {
                                   this.Invoke((MethodInvoker)delegate() { richTextBoxReceived.AppendText("\n" + Encoding.ASCII.GetString(buffer)); });
                              }                              
                         }
                    }                                                                 
                    catch (Exception ex)
                    {
                         MessageBox.Show(ex.Message);
                    }                    
               }
          }

          private void buttonStart_Click(object sender, EventArgs e)
          {
               try
               {
                    server.Bind((EndPoint) new IPEndPoint(IPAddress.Any,SERVER_PORT));
                    server.Listen(2);
                    client = server.Accept();
                    richTextBoxReceived.AppendText("\nClient Conected : " + (client.RemoteEndPoint as IPEndPoint).Address + " | " + (client.RemoteEndPoint as IPEndPoint).Port + " | " + (client.RemoteEndPoint as IPEndPoint).AddressFamily);
                    receiver.Start();
               }
               catch (Exception ex)
               {
                    MessageBox.Show(ex.Message);
               }
          }

          private void buttonSend_Click(object sender, EventArgs e)
          {
               if (client.Connected && textBoxSend.Text != String.Empty)
               {
                    buffer = new byte[100];
                    buffer = Encoding.ASCII.GetBytes(textBoxSend.Text);
                    try
                    {
                         client.Send(buffer);
                         this.Invoke((Action)delegate() { richTextBoxReceived.AppendText("\nSent : " + textBoxSend.Text); });
                         textBoxSend.Clear();
                    }
                    catch (Exception ex)
                    {
                         MessageBox.Show(ex.Message);
                    }                    
               }
          }
     }
}

我对这个问题感到沮丧,我需要一些帮助,我提前感谢。

1 个答案:

答案 0 :(得分:0)

为了进行健全性检查,为什么不尝试修改您的流以发送和接收字符串,以便我们可以删除所有字节转换内容。只是为了尝试缩小问题范围。只需在Android上使用C#和printwriter中的streamreader即可。