我创建了一个简单的网络测试应用程序。 但它不起作用,并且总是在 Socket() 处抛出错误。 我尝试使用 getMessage() 检查错误消息,但没有打印任何消息。 我该怎么办?
public static void main(String args[]){
ServerSocket serverSocket = null;
Socket socket = null;
try{
serverSocket = new ServerSocket(14100);
socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
byte[] arr = new byte[100];
in.read(arr);
System.out.println(new String(arr));
String str = "Hello Client";
out.write(str.getBytes());
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
try{
socket.close();
}
catch(Exception ignored){}
try{
serverSocket.close();
}
catch(Exception ignored){}
}
}
下面是客户端的 android 代码。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
TextView tv = (TextView) findViewById(R.id.id_tv);
Socket socket = null;
try{
socket = new Socket("192.168.0.52",14100);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
String str = "Hello Server";
out.write(str.getBytes());
byte arr[] = new byte[100];
in.read(arr);
tv.setText(new String(arr));
}
catch(UnknownHostException uhe){
}
catch(IOException ioe){
}
catch(Exception e){
}
finally{
try{
socket.close();
}
catch(Exception ignored){
}
}
}
当然,我在AndroidManifest.xml中添加了android的权限
最佳答案
将套接字代码从 UI 主线程 onCreate()
移至 AsyncTask
或常规线程。
为了进行快速测试,请将所有套接字代码包装到一个线程中,如下所示:
new Thread() {
public void run() {
// Move your socket code here for a quick test
}
}.start();
关于java - Android Socket 错误且无消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27210152/