我已建立客户端服务器连接并且连接良好但套接字始终返回null,我不知道原因。
服务器是 MATLAB ,没有问题,运行良好。当我尝试在浏览器中编写服务器的ip时,它会向我提供客户端应该收到的消息。
这是服务器代码
data = 'Hello World..\n'
tcpipServer = tcpip('0.0.0.0',80,'NetworkRole','Server');
set(tcpipServer,'OutputBufferSize',length(data)+1);
fopen(tcpipServer);
fwrite(tcpipServer,data);
fclose(tcpipServer);
这是客户端代码
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends ActionBarActivity {
Socket socket;
TextView txt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt1 = (TextView) findViewById(R.id.txt1);
final byte[] data = new byte[1024];
new Thread(new Runnable() {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.185.10");
socket = new Socket(serverAddr, 80);
socket.getInputStream().read(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
txt1.setText(new String(data));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
以下是套接字始终等于null的问题
socket = new Socket(serverAddr, 80);
注意:它连接到服务器但没有收到任何东西 我甚至在清单上有互联网许可。