我正试图让我的 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 因为我无法让 wifi 在模拟器上工作(这是一个简单的修复)所以当在我的模拟器上运行代码时它可以工作,不空字符串;但是当在我真正的 android 上运行时,它返回 null,我能想到的只有一个原因会导致这种情况发生,我使用的 sdk 与我的 androids os 版本(较旧)不匹配,这可能是原因还是我错了吗?
编辑:我明白了,事实证明我只需要从 androids sdk manager 安装一些 api 10 包,现在就像一个魅力:)