我试图让我的android与我的电脑谈话,我几乎已经知道了。我可以通过互联网发送字符串到我的电脑和所有,但只有一个问题:当我的电脑读取字符串,他们是空的!无声字符串的秘密(服务器接收来自Android客户端的空字符串)
这里的客户端代码:
public class ClientActivity extends Activity implements View.OnClickListener{
EditText ip1,ip2,ip3,ip4, message, port;
TextView con;
Button send;
InetAddress inet;
Socket s;
OutputStream out;
PrintWriter output;
int sip;
int rport;
byte[] ip;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ip1 = (EditText) findViewById(R.id.etIP1);
ip2 = (EditText) findViewById(R.id.etIP2);
ip3 = (EditText) findViewById(R.id.etIP3);
ip4 = (EditText) findViewById(R.id.etIP4);
port = (EditText) findViewById(R.id.etPort);
message = (EditText) findViewById(R.id.etMessage);
send = (Button) findViewById(R.id.bSend);
con = (TextView) findViewById(R.id.tvCon);
ip = new byte[4];
send.setOnClickListener(this); }
@Override
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.bSend:
try{
rport = Integer.parseInt(port.getText().toString());
} catch (NumberFormatException e){
con.setText(e.toString());
break;
}
try{
sip = Integer.parseInt(ip4.getText().toString());
sip = (sip << 8) + Integer.parseInt(ip3.getText().toString());
sip = (sip << 8) + Integer.parseInt(ip2.getText().toString());
sip = (sip << 8) + Integer.parseInt(ip1.getText().toString());
} catch (NumberFormatException e){
con.setText(e.toString());
break;
}
ip[0] = (byte)(0xff & sip);
ip[1] = (byte)(0xff & (sip >> 8));
ip[2] = (byte)(0xff & (sip >> 16));
ip[3] = (byte)(0xff & (sip >> 24));
try {
inet = InetAddress.getByAddress(ip);
s = new Socket(inet, rport);
out = s.getOutputStream();
output = new PrintWriter(out);
output.println(message.getText().toString());
con.setText("Message Sent");
s.close();
} catch (UnknownHostException e) {
con.setText(e.toString());
} catch (IOException e) {
con.setText(e.toString());
}
break;
}
}
}
下面是该服务器的代码:
public class Main {
public static void main(String[] args) {
try {
Boolean end = false;
ServerSocket ss = new ServerSocket(4331);
while(!end){
//Server is waiting for client here, if needed
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
System.out.println(""+st);
s.close();
}
ss.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
任何帮助都将不胜感激。
编辑:我发现了问题;最初我没有使用模拟器来测试我的代码,我使用我的实际Android,因为我无法让无线网络模拟器工作(这是一个简单的修复),所以当我的模拟器上运行代码它的工作原理,没有空字符串;但是当我的真正的Android上运行时,它返回null,只有一个原因,我可以想到会导致这种情况发生,我使用的SDK不匹配我的Android操作系统版本(它的旧版本)可能是这个原因或我错了吗?
编辑:我知道了,原来我只需要安装一些API从机器人SDK管理器10包就像现在一个魅力:)
您是否在wifi上使用您的实际设备或超过3g/4g?许多运营商阻止非标准端口,有时在他们的网络,有时在设备本身 –
实际的WiFi我买了三星银河媒体播放器,它没有电话功能 – MrFuzzles