Socket服务器和客户端单项通讯
Android客户端连接不上服务器是什么原因啊?求大神指教,拜谢!服务器的代码!
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer {
public static void main(String[] args) {
//创建一个ServerSocket,用于监听客户端Socket的连接请求
try {
ServerSocket ss=new ServerSocket(30000);
//采用循环不断的方式接受来自客户端的请求
while(true){
//每当接受客户端的请求时,服务器长生一个对应的socket
Socket s=ss.accept();
OutputStream os=s.getOutputStream();
os.write("接受大神的洗礼吧!".getBytes("UTF-8"));
System.out.println("os:os");
//关闭输出流,关闭Socket
os.close();
s.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端的代码(Android部分)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.EditText;
public class SimpleClient extends Activity {
private EditText show;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show=(EditText)findViewById(R.id.show);
try {
//建立到连接远程服务器的Socket
Socket socket=new Socket(InetAddress.getLocalHost(),30000);
//将Socket对应的输入流包装成BufferedReader
BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//进行普通io操作
String line=br.readLine();
Log.d("SimpleClient", "line:"+line);
show.setText("客户端的信息是:"+line);
//关闭输入流 socket
br.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Socket
补充:云计算 , 云安全