安卓TCP/IP套接字无法向计算机发送数据

4

我试图制作一个应用程序,将数据从Android发送到计算机(Java到VB.net)。在Eclipse Java项目中,数据发送正在工作,但在Android项目中不起作用。 但我有一个问题。我的计算机中没有传入的数据到Visual Basic。 VB代码:

 Imports System.Net.Sockets
 Imports System.Threading
 Imports System.IO

Public Class Form1

Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = ""

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ListThread As New Thread(New ThreadStart(AddressOf Listening))
    ListThread.Start()
End Sub

Private Sub Listening()
    Listener.Start()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Client = New TcpClient("192.168.100.3", 65535)

    Dim Writer As New StreamWriter(Client.GetStream())
    Writer.Write(TextBox2.Text)
    Writer.Flush()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    If Listener.Pending = True Then
        Message = ""
        Client = Listener.AcceptTcpClient()

        Dim Reader As New StreamReader(Client.GetStream())
        While Reader.Peek > -1
            Message = Message + Convert.ToChar(Reader.Read()).ToString
        End While

        MsgBox(Message, MsgBoxStyle.OkOnly)
    End If
 End Sub

Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As     System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Listener.Stop()
End Sub

End Class

Java 代码:

package com.example.androidclient2;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    serverMessage=(TextView)findViewById(R.id.textView1);
}
public void Start(View view)
{
m_objThreadClient=new Thread(new Runnable() {
      public void run()
       {
          try 
           {
             clientSocket= new Socket("192.168.100.3",65535);
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
             oos.writeObject("Hellow there");
             Message serverMessage= Message.obtain();
             ObjectInputStream ois =new     ObjectInputStream(clientSocket.getInputStream());
             String strMessage = (String)ois.readObject();
            serverMessage.obj=strMessage;
            mHandler.sendMessage(serverMessage); 
            oos.close();
            ois.close();
           } 
           catch (Exception e) 
           {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }
        });

 m_objThreadClient.start();

}
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
    messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String servermessage)
{
serverMessage.setText(""+servermessage);
}

}

And Thanks For The help .


你的安卓设备和电脑是否在同一本地网络上(即192.168.100.x)?另外,请不要使用端口65535。 - Cruncher
是的,可以。为什么不选择端口65535?应该选择哪一个? - fares
仅仅因为它是最后一个端口号,并不意味着它不会发生端口冲突的可能性更小。在私有端口范围49152到65535中选择一个端口是不错的选择,只需避开这些范围中的前10个和后10个端口。在中间区域随意选择一个端口即可。 - Cruncher
你也可以使用已注册的端口范围,并选择未分配的端口。https://dev59.com/5XVC5IYBdhLWcg3w9GLM - Cruncher
啊哈...我明白了,我认为获取最后一个数字会更好一些。 但是这里有什么问题吗? 谢谢。 - fares
1个回答

7

今天我刚刚在安卓上创建并测试了这个类:

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class TcpClient {

private static final String TAG = TcpClient.class.getSimpleName();

private Socket socket;
private PrintWriter out;
private boolean connected;

public TcpClient()
{
    socket = null;
    out = null;
    connected = false;
}


public void connect(Context context, String host, int port)
{
    new ConnectTask(context).execute(host, String.valueOf(port));
}

private class ConnectTask extends AsyncTask<String, Void, Void> {

    private Context context;

    public ConnectTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        showToast(context, "Connecting..");
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(Void result) {
        if (connected) {
            showToast(context, "Connection successfull");
        }           
        super.onPostExecute(result);
    }

    private String host;
    private int port;

    @Override
    protected Void doInBackground(String... params) {
        try {
            String host = params[0];
            int port = Integer.parseInt(params[1]);
            socket = new Socket(host, port);
            out = new PrintWriter(socket.getOutputStream(), true);
        } catch (UnknownHostException e) {
            showToast(context, "Don't know about host: " + host + ":" + port);
            Log.e(TAG, e.getMessage());
        } catch (IOException e) {
            showToast(context, "Couldn't get I/O for the connection to: " + host + ":" + port);
            Log.e(TAG, e.getMessage());
        }
        connected = true;
        return null;
    }


}

public void disconnect(Context context)
{
    if ( connected )
    {
        try {
            out.close();
            socket.close();
            connected = false;
        } catch (IOException e) {
            showToast(context, "Couldn't get I/O for the connection");
            Log.e(TAG, e.getMessage());
        }            
    }
}


/**
 * Send command to a Pure Data audio engine. 
 */
public void send(String command)
{
    if ( connected ) out.println(command +";");   
}

private void showToast(final Context context, final String message) {
    new Handler(context.getMainLooper()).post(new Runnable() {

        @Override
        public void run() {
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        }
    });
}
}

尽管我在您的代码中没有看到明显的错误,但这可能会对您有所帮助。

该设备是否与您的计算机在同一WiFi网络中?例如,通过USB连接是行不通的。


它没有错误。你确定已经导入了正确的包吗?我将把导入添加到代码中。 - cYrixmorten
好的,这个有效。但是为什么要发送两次?我有一个正在运行的C#应用程序来检查连接的应用程序数量,每次我加载该活动时,它都会说“一个新应用程序已连接”,并且会说两次。 - ssi-anik
正如@fares所说,如果由于某些异常而未连接到远程主机,那么出现错误是正确的,您正在显示我已连接?根据错误或成功更改连接状态。 - ssi-anik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接