我有一个应用程序将消息发送到套接字服务器,当我使用模拟器工作时,但是当我去智能手机时,应用程序不会发送。
The server is created by VB.NET. A simple console that receives messages.
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Public Module MainModule
Dim server As New TcpListener(IPAddress.Parse("10.0.0.100"), 11000)
Dim client As New TcpClient
Dim stream As NetworkStream
Public Sub Main()
Dim str As String
server.Start()
client = server.AcceptTcpClient
stream = client.GetStream()
Dim r_byt(client.ReceiveBufferSize) As Byte
stream.Read(r_byt, 0, client.ReceiveBufferSize)
str = Encoding.ASCII.GetString(r_byt)
Console.WriteLine(str)
Console.ReadLine()
End Sub
Private Sub Responce_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("Got it" & vbCr)
stream.Write(s_byt, 0, s_byt.Length)
stream.Flush()
stream.Close()
client.Close()
server.Stop()
End Sub
End Module
现在我将展示将消息发送到服务器的Android代码。
package com.javacodegeeks.android.androidsocketclient;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Client extends Activity {
private static final String SERVER_IP = "10.0.0.100";
private static final int SERVER_PORT = 11000;
private Socket socket;
private EditText InputText = null;
private Button ButtonSend = null;
private TextView LabelReceived = null;
private Thread thread = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputText = (EditText)findViewById(R.id.InputText);
ButtonSend = (Button)findViewById(R.id.ButtonSend);
LabelReceived = (TextView)findViewById(R.id.LabelReceived);
thread = new Thread(new ClientThread());
if (thread != null) {
thread.start();
}
ButtonSend.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
if (socket != null) {
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println(InputText.getText().toString());
out.flush();
out.close();
} else {
LabelReceived.setText("socket is null!");
}
} catch (Exception e) {
LabelReceived.setText(e.getMessage());
}
}
});
}
class ClientThread implements Runnable {
public void run() {
try {
InetAddress IAddress = InetAddress.getByName(SERVER_IP);
socket = new Socket(IAddress, SERVER_PORT);
} catch (Exception e) {
socket = null;
}
}
}
}
我也使用标签来显示错误,当我按下发送按钮时出现“socket is null”。
这些代码在我上学之前今天起作用,但是当我到达时,我试图再次这样做,不再有效。所以我认为这是一个简单的问题,但它是非常隐蔽的。
答案 0 :(得分:0)
尝试在AsyncTask或服务中将您的请求提取到服务器
public class MyTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
something
}
protected void onPostExecute(Void result) {
something
}
protected Void doInBackground(Void... arg0) {
something
}
并将其称为
MyTask mt = new MyTask();
mt.execute();
答案 1 :(得分:-1)
问题与我的预期大不相同。只是我的防病毒软件阻止了连接,我添加了一个例外,现在套接字正在工作。