Android Socket服务器 Servlet服务器

Android Socket服务器 与 Servlet 服务器

一、   Servlet服务器

打开Myeclipse新建Java WebProject

新建Servlet 我写的就是一个UserServlet 注意修改映射地址(Mapping URL)随意吧  可以不改

建好之后 删除乱七八糟注释,通过doget调用dopost ,之后在dopost中实现响应客户端的操作

ServerSocket serverSocket = null;
	try {
    //设置Socket端口 因为Servlet 服务器端已经占用了8080 随意设置建议 1024 以外
		 serverSocket =  new ServerSocket(8081);            
		System.out.println("Socket 服务器已启动");
		while (true) {
			Socket socket = serverSocket.accept();
		 // 接受客户端传递的数据  并设置字符编码为utf-8  否则会出现中文乱码
			InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "utf-8"); 
			char[] cbuf = new char[100];
			isr.read(cbuf);
			System.out.println(" 接收来自服务器的数据 action =  "+String.copyValueOf(cbuf));
				
			DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
			outputStream.write("hello android client. this is socket server".getBytes("utf-8"));
			outputStream.flush();
			outputStream.close();
			isr.close();
			socket.close();
		}
	} catch (IOException e) {
		System.out.println("  socket server failed  whyyyyyyyyy ");
		e.printStackTrace();
	}
		
}


二、   Socket服务器

新建Java Project 

ServerSocket serverSocket = null;
	try {
    //设置Socket端口 因为Servlet 服务器端已经占用了8080 随意设置建议 1024 以外
		 serverSocket =  new ServerSocket(8081);            
		System.out.println("Socket 服务器已启动");
		while (true) {
			Socket socket = serverSocket.accept();
		 // 接受客户端传递的数据  并设置字符编码为utf-8  否则会出现中文乱码
			InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "utf-8"); 
			char[] cbuf = new char[100];
			isr.read(cbuf);
			System.out.println(" 接收来自服务器的数据 action =  "+String.copyValueOf(cbuf));
				
			DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
			outputStream.write("hello android client. this is socket server".getBytes("utf-8"));
			outputStream.flush();
			outputStream.close();
			isr.close();
			socket.close();
		}
	} catch (IOException e) {
		System.out.println("  socket server failed  whyyyyyyyyy ");
		e.printStackTrace();
	}
		
}

Android 客户端 新起线程调用连接服务器的方法

new Thread(new Runnable() {

	@Override
	public void run() {
		if (falg) {  
			String name = et_name.getText().toString();
			String pwd = et_pwd.getText().toString();
			if (!(StringUtil.checknull(name) || StringUtil.checknull(pwd))) {
	   			User user = new User(name, pwd);
//				UserManager.getInstance().loginAndReg(Const.USER_REG , user, handler);
				Gson gson = new Gson();   // 通过Gson 将对象快速转化为Json数据
//				ConnectServer.getInstance().socketTest(gson.toJson(user) , handler);
						
				ConnectServer.getInstance().httpPost(gson.toJson(user), new ConnectServer.HttpCallBack() {
						
					@Override
				public void responseBack(String response) {
					System.out.println(" 接受服务器反馈的数据 response =  "+response);
	    			}
				}, handler);
			}
		}
	}
}).start();

// 实现回调接口 
public interface HttpCallBack {

	public void responseBack(String request);

}
	
String response = ""; // 服务器端返回数据
	try {
		json = "act=" + json;
		byte[] data = json.getBytes();
    // 连接服务器路径
		URL url = new URL("http://10.2.0.1:8080/JavaWebwDemo/userServlet");
    // 根据url打开网络连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // 设置连接属性 超时时间 设置 输入 输出 不适用缓存 使用post方法
    // 字符集(UTF-8)数据长度(data.length)内容类型("application/x-www-form-urlencoded")
		conn.setConnectTimeout(5 * 1000);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content_Length",
		String.valueOf(data.length));
		conn.setRequestProperty("Content-Type",
    		"application/x-www-form-urlencoded");

	// 建立连接
		conn.connect();
		DataOutputStream outputStream = new DataOutputStream(
			conn.getOutputStream());
	// 将数据写到输出流
		outputStream.write(data);
		outputStream.flush();
		outputStream.close();
	// 获取返回数据
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			InputStream inputStream = conn.getInputStream();
			response = in2Str(inputStream, "UTF-8");   // 从输入流读取数据 
		} else {
			System.out.println(" 请求服务器数据失败  " + conn.getResponseCode());
		}
			
	} catch (Exception e) {
		e.printStackTrace();
		handler.obtainMessage(Const.SERVER_TIMEOUT).sendToTarget();
	}
	if (callBack == null)
		return;
	callBack.responseBack(response);

下载地址: 全部免豆下载
UserServlet  ---    http://download.csdn.net/detail/ouyangjiluo/7079385
ServerMain (Socket)  ---    http://download.csdn.net/detail/ouyangjiluo/7079381
MainActivity  ----  http://download.csdn.net/detail/ouyangjiluo/7079365
ConnectServer ---   http://download.csdn.net/detail/ouyangjiluo/7079357

你可能感兴趣的:(Android)