Java Socket、 Android网络工具类

java.net.InetAddress

获得本机地址对象,InetAddress.getLocalHost();

获得表示远程地址的对象,InetAddress.getByName(ip或主机名);

getHostAddress(); ip     getHostName(); 主机名

java.net.ServersSocket

ServerSocket ss = new ServerSocket(端口号);

Socket s = ss.accept(); //阻塞方法

java.net.Socket

Socket s = new Socket( ip , 端口号); 

获得双向通行的流:s.getInputStream(); s.getOutputStream();

设置接收数据超时:s.setSoTimeout(毫秒);

关闭:1)关闭Socket,2)关闭ServerSocket

简单的Client/Server程序

1. 客户端程序

  import java.io.*;

  import java.net.*;

  public class TalkClient {

    public static void main(String args[]) {

      try{

        Socket socket=new Socket("127.0.0.1",4700);

        //向本机的4700端口发出客户请求

        BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));

        //由系统标准输入设备构造BufferedReader对象

        PrintWriter os=new PrintWriter(socket.getOutputStream());

        //由Socket对象得到输出流,并构造PrintWriter对象

        BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //由Socket对象得到输入流,并构造相应的BufferedReader对象

        String readline;

        readline=sin.readLine(); //从系统标准输入读入一字符串

        while(!readline.equals("bye")){

        //若从标准输入读入的字符串为 "bye"则停止循环

          os.println(readline);

          //将从系统标准输入读入的字符串输出到Server

          os.flush();

          //刷新输出流,使Server马上收到该字符串

          System.out.println("Client:"+readline);

          //在系统标准输出上打印读入的字符串

          System.out.println("Server:"+is.readLine());

          //从Server读入一字符串,并打印到标准输出上

          readline=sin.readLine(); //从系统标准输入读入一字符串

        } //继续循环

        os.close(); //关闭Socket输出流

        is.close(); //关闭Socket输入流

        socket.close(); //关闭Socket

      }catch(Exception e) {

        System.out.println("Error"+e); //出错,则打印出错信息

      }

  }

}

 2. 服务器端程序

  import java.io.*;

  import java.net.*;

  import java.applet.Applet;

  public class TalkServer{

    public static void main(String args[]) {

      try{

        ServerSocket server=null;

        try{

          server=new ServerSocket(4700);

        //创建一个ServerSocket在端口4700监听客户请求

        }catch(Exception e) {

          System.out.println("can not listen to:"+e);

        //出错,打印出错信息

        }

        Socket socket=null;

        try{

          socket=server.accept();

          //使用accept()阻塞等待客户请求,有客户

          //请求到来则产生一个Socket对象,并继续执行

        }catch(Exception e) {

          System.out.println("Error."+e);

          //出错,打印出错信息

        }

        String line;

        BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));

         //由Socket对象得到输入流,并构造相应的BufferedReader对象

        PrintWriter os=newPrintWriter(socket.getOutputStream());

         //由Socket对象得到输出流,并构造PrintWriter对象

        BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));

         //由系统标准输入设备构造BufferedReader对象

        System.out.println("Client:"+is.readLine());

        //在标准输出上打印从客户端读入的字符串

        line=sin.readLine();

        //从标准输入读入一字符串

        while(!line.equals("bye")){

        //如果该字符串为 "bye",则停止循环

          os.println(line);

          //向客户端输出该字符串

          os.flush();

          //刷新输出流,使Client马上收到该字符串

          System.out.println("Server:"+line);

          //在系统标准输出上打印读入的字符串

          System.out.println("Client:"+is.readLine());

          //从Client读入一字符串,并打印到标准输出上

          line=sin.readLine();

          //从系统标准输入读入一字符串

        }  //继续循环

        os.close(); //关闭Socket输出流

        is.close(); //关闭Socket输入流

        socket.close(); //关闭Socket

        server.close(); //关闭ServerSocket

      }catch(Exception e){

        System.out.println("Error:"+e);

        //出错,打印出错信息

      }

    }

  }

package com.mdream.shenmo_alpha.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EncodingUtils;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpUtils {
	public static boolean HTTP_RESULT;
	private static String result;
	public static List<Cookie> mCookies = new ArrayList<Cookie>();
	static final String digits = "0123456789ABCDEF";

	public static String encode(String s, String enc)
			throws UnsupportedEncodingException {
		if (s == null || enc == null) {
			throw new NullPointerException();
		}
		"".getBytes(enc);
		StringBuilder buf = new StringBuilder(s.length() + 16);
		int start = -1;
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
					|| (ch >= '0' && ch <= '9')
					|| " .-*_/:?=&".indexOf(ch) > -1) {
				if (start >= 0) {
					convert(s.substring(start, i), buf, enc);
					start = -1;
				}
				if (ch != ' ') {
					buf.append(ch);
				} else {
					buf.append('+');
				}
			} else {
				if (start < 0) {
					start = i;
				}
			}
		}
		if (start >= 0) {
			convert(s.substring(start, s.length()), buf, enc);
		}
		return buf.toString();
	}

	private static void convert(String s, StringBuilder buf, String enc)
			throws UnsupportedEncodingException {
		byte[] bytes = s.getBytes(enc);
		for (int j = 0; j < bytes.length; j++) {
			buf.append('%');
			buf.append(digits.charAt((bytes[j] & 0xf0) >> 4));
			buf.append(digits.charAt(bytes[j] & 0xf));
		}
	}

	public static String httpGet(String url) {
		HttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
				10000);
		httpClient.getParams().setIntParameter(
				HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
		try {
			String urlEncode = encode(url, "UTF-8");
			HttpGet request = new HttpGet(urlEncode);
			HttpResponse response;
			if (mCookies != null) {
				for (int i = 0; i < mCookies.size(); i++) {
					request.addHeader("Cookie", mCookies.get(i).getName() + "="
							+ mCookies.get(i).getValue());
				}
			}
			response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HTTP_RESULT = true;
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity, HTTP.UTF_8);
				CookieStore mCookieStore = ((AbstractHttpClient) httpClient)
						.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				List<Integer> mCookieIndex = new ArrayList<Integer>();
				if (mCookies != null) {
					for (int i = 0; i < mCookies.size(); i++) {
						for (int j = 0; j < cookies.size(); j++) {
							boolean cookieEq = mCookies.get(i).getName()
									.equals(cookies.get(j).getName());
							if (cookieEq) {
								mCookieIndex.add(i);
							}
						}
					}
					for (int i = 0; i < mCookieIndex.size(); i++) {
						int index = mCookieIndex.get(i);
						mCookies.remove(index);
					}
				}
				mCookies.addAll(cookies);
			} else {
				HTTP_RESULT = false;
			}
		} catch (Exception e) {
			HTTP_RESULT = false;
			mCookies.clear();
			System.out.println("网络连接失败 HttpUtils!");
			e.printStackTrace();
		}
		return result;
	}

	public static String readFromSDcard(String fileName) {
		String fileContent = "";
		try {
			File f = new File("/mnt/sdcard/" + fileName);
			if (f.isFile() && f.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(f), "gbk");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent += line;
				}
				read.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileContent;
	}

	public static String getFromRaw(Context context, String filename) {
		String result = "";
		try {
			AssetManager am = context.getAssets();
			InputStream in = am.open(filename);
			int lenght = in.available();
			byte[] buffer = new byte[lenght];
			in.read(buffer);
			result = EncodingUtils.getString(buffer, "gbk");
			in.close();
		} catch (Exception e) {
		}
		return result;
	}

	/**
	 * 从Assets中读取图片
	 * 
	 * @throws IOException
	 */
	public static Bitmap getImageFromAssetsFile(Context context, String fileName)
			throws IOException {
		AssetManager am = context.getResources().getAssets();
		BitmapFactory.Options opt = new BitmapFactory.Options();
		opt.inPreferredConfig = Bitmap.Config.RGB_565;
		opt.inPurgeable = true;
		opt.inInputShareable = true;
		// 获取资源图片
		InputStream is = am.open(fileName);
		Bitmap bitmap = Bitmap
				.createBitmap(BitmapFactory.decodeStream(is, null, opt),
						GConstant.NPCPOS_X, GConstant.NPCPOS_Y,
						GConstant.NPC_WIDTH_, GConstant.NPC_HEIGHT_);

		is.close();
		return bitmap;
	}
}

public String textPost(String urlPath, String params) {
		StringBuffer sb = new StringBuffer();
		BufferedReader br = null;

		try {
			URL url = new URL(urlPath);
			//打开连接  
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			//设置提交方式  
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod("POST");
			//post方式不能使用缓存  
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			//设置连接超时时间  
			conn.setConnectTimeout(6 * 1000);
			//配置本次连接的Content-Type,配置为application/x-www-form-urlencoded  
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//维持长连接  
			conn.setRequestProperty("Connection", "Keep-Alive");
			//设置浏览器编码  
			conn.setRequestProperty("Charset", "UTF-8");
			DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
			//将请求参数数据向服务器端发送  
			dos.writeBytes(params);
			dos.flush();
			dos.close();
			if (conn.getResponseCode() == 200) {
				//获得服务器端输出流  
				br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

				int c = 0;
				while ((c = br.read()) != -1) {
					sb.append((char) c);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值