问题描述
Android客户端连接不上服务器是什么原因啊?求大神指教,拜谢!服务器的代码!importjava.io.IOException;importjava.io.OutputStream;importjava.net.ServerSocket;importjava.net.Socket;publicclassSimpleServer{publicstaticvoidmain(String[]args){//创建一个ServerSocket,用于监听客户端Socket的连接请求try{ServerSocketss=newServerSocket(30000);//采用循环不断的方式接受来自客户端的请求while(true){//每当接受客户端的请求时,服务器长生一个对应的socketSockets=ss.accept();OutputStreamos=s.getOutputStream();os.write("接受大神的洗礼吧!".getBytes("UTF-8"));System.out.println("os:os");//关闭输出流,关闭Socketos.close();s.close();}}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}
客户端的代码(Android部分)importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.InetAddress;importjava.net.Socket;importjava.net.UnknownHostException;importandroid.os.Bundle;importandroid.app.Activity;importandroid.util.Log;importandroid.view.Menu;importandroid.widget.EditText;publicclassSimpleClientextendsActivity{privateEditTextshow;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);show=(EditText)findViewById(R.id.show);try{//建立到连接远程服务器的SocketSocketsocket=newSocket(InetAddress.getLocalHost(),30000);//将Socket对应的输入流包装成BufferedReaderBufferedReaderbr=newBufferedReader(newInputStreamReader(socket.getInputStream()));//进行普通io操作Stringline=br.readLine();Log.d("SimpleClient","line:"+line);show.setText("客户端的信息是:"+line);//关闭输入流socketbr.close();socket.close();}catch(UnknownHostExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}catch(Exceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.getMenuInflater().inflate(R.menu.activity_main,menu);returntrue;}}
解决方案
解决方案二:
代码的问题看看有没有空指针