网络通信

(written in  2012-08-09 22:29:46


无线网络类型

  • 无线广域网WWAN
  • 无线城域网WMAN
  • 无线局域网WLAN
  • 无线个域网WPAN
  • 低速率无线个域网LR-WPAN

 

网络相关的接口

  • java.net.*

try{
//定义地址
URL url = new URL("http://www.google.com");
HttpURLConnection http = (HttpURLConnection) url.openConnection();
//得到连接状态
int nRC = http.getResponseCode();
if(nRC == HttpURLConnection.HTTP_OK){
//取得数据
InputStream is = http.getInputStream();
//处理数据
}
}catch(Exception e){
}


  • org.apache.*

try{
//创建HttpClient
//这里使用DefaultHttpClient表示默认属性
HttpClient hc = new DefaultHttpClient();
//HttpGet实例
HttpGet get = new HttpGet("http://www.google.com");
//连接
HttpRespone rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
InputStream is  = rp.getEntity().getContent();
}
}catch(Exception e){
}


  • android.net.*

try{
//ip地址
InetAddrass inetAddress = InetAddress.getByName("192.168.1.110");
//端口
Socekt client = new Socket(inetAddress,61203,true);
//取得数据
InputStream in  = client.getInputStream();
OutputStream out = client.getOutputStream();\
//处理数据。。。
put.close();
in.close();
client.close();
 
}catch(UnknownHostException e){
……
}catch(IOException e){
……
}
 


HTTP通信

HttpURLConnection接口

例:GET方式

public class Acitvity02 extends Activity{
private final String DEBUG_TAG = "Activity02";
 
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
 
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
//http地址
String httpUrl = "http://192.168.1.110:8080/http1.jsp?par=abc";
//获取数据
String resultData = "";
URL url = null;
try{
//构造一个URL对象
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.e(DEBUG_TAG,"MalformedURILException");
}
if(url != null){
try{
//使用HttpConnection打开连接
HttpURLConnection urlConn = (HttpURLConnection)url.openCounnection();
//得到读取的内容
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
//输出创建BufferedReader
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据
while(((inputLine = buffer.readLine() != null)){
resultData += inputLine + "\n";
}
in.close();
urlConn.disconnect();
 
//设置显示内容
if(resultData ! = null){
mTextView.setTextView(resultData);
}else{
mTextView.setTextView("读取的内容为NULL");
}
}catch(IOException e){
Log.e(DEBUG_TAG,"IOException");
}
}else{
Log.e(DEBUG_TAG,"Url NULL");
}
 
//设置按键事件
Button button_back = (Button)findViewById(R.id.Button_back);
button_back.setOnClickListener(new Button.onClickListener(){
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(Activity02.this,Activity01.class);
startActivity(intent);
Activity02.this.finish();
}
});
 
}
}


 

例:POST方式

public class Activity04 extends Activity{
 
private fianl String DEBUG_TAG  = "test";
 
public void onCreate(Bundle savedInstanceState){
 
super.onCreate(savedInstancedState);
setContentView(R.layout.http);
 
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
String resultData = "";
URL url = null;
try{
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.e(DEBUG_TAG,"MalformedURLException");
}
 
if(url != null){
try{
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCached(false);
urlConn.setInstanceFollowRedirects(true);
 
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
String content = "par=" + URLEncoder.encode("ABCDEFG","gb2312");
//将要上传的内容写入
out.writeBytes(conent);
out.flush();
out.close();
 
//获取数据
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
while(((inputLine = reader.readLine()) != null)){
resultData += inputLine + "\n";
}
reader.close();
urlConn.disconnect();
if(resultData != null){
mTextView.setText(resultData);
}else{
mTextView.setText("读取的内容为NULL");
}
}catch(IOException e){
Log.e(DEBUG_TAG,"IOException");
}
}else{
Log.e(DEBUG_TAG,"Uri NULL");
}
 
Button button_Back = (Button)findViewById(R.id.Button_Back);
button_Back.setOnClickListener(new Button.OnClickListener(){
 
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(Activity04.this,Activity01.class);
startActivity(intent);
Activity04.this.finish();
}
});
}
}


 

显示网络上的图片

 

public Bitmap GetNetBitmap(String url){
URL imageUrl  = null;
Bitmap bitmap = null;
try{
imageUrl = new URL(url);
}catch(MalformedURLException e){
Log.e(DEBUG_TAG,e.getMessager());
}
 
try{
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
}catch(IOException e){
Log.e(DEBUG_TAG,e.getMessage();
}
return bitmap;
}


 

HttpClient接口

抽象方法

ClientConnectionManager

关闭所有无效,超时的连接

closeIdleConnections

关闭空闲的连接

releaseConnection

释放一个连接

requestConnection

请求一个新的连接

Shudown

关闭管理器并释放资源

例:GET方式

public class Activity02 extends Activity{
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
 
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
String httpUrl="http://192.168.1.110:8080/httpget.jsp?=par=HttpClient_android_Get";
 
//连接对象
HttpGet httpRequest = new HttpGet(httpUrl);
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView.setView(strResult);
}else{
mTextView.setText("请求错误!");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
 
//设置按讲事件监听
Button button_Back = (Button)findViewById(R.id.Button_Back);
button_Back.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent();
intent.setClas(Activity02.this,Activity01.class);
startActivity(intent);
Activity02.this.finish();
}
});
}
}


 

例:POST方式

public class Activity03 extends Activity{
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.http);
 
TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//连接对象
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair来保存还要传递的post参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加要传递的参数
params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
try{
//设置字符集
HttpEnity httpentity = new UrlEncodedFormEntity(params,"gb2312");
//请求
httpRequest.setEnity(httpentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse  = httpResponse.execute(httpRequest);
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
mTextView.setText(strResult);
}else{
mTextView.setText("请求错误!");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
 
//监听事件
Button button_Back = (Button)findViewById(R.id.Button_Back);
button_Back.setOnClickListener(new Button.OnClickListener()){
public void onClick(View v){
Intent intent = new Intent();
intent.setClass(Activity03.this,Activity01.class);
startActivity(intent);
Activity03.this.finish();
}
});
}
}


 

实时更新

例:

public class Activity01 extend Activity{
private final String DEBUG_TAG = "Activity02";
private TextView mTextView;
private Button mButton;
 
public void onCreate(Bundle savedInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
 
mTextView = (TextView)this.findViewById(R.id.TextView01);
mButton = (Button)this.findViewById(R.id.Button01);
mButton.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
refresh();
}
});
 
new Thread(mRunnable).start();
}
 
private void refresh(){
String httpUrl = "http://192.168.1.110:8080/date.jsp";
String resultData = "";
URL url = null;
try{
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.e(DEBUG_TAG,"MalformedURLException");
}
 
if(url != null){
try{
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
 
//使用循环来读取获得数据
while(((inputLine = buffer.readLine())!=null){
resultData += inputLine +"\n";
}
 
in.close();
urlConn.disconnect();
if(resultData !=null){
mTextView.setText(resultData);
}else{
mTextView.setText("读取内容为null");
}
}catch(IOException e){
Log.e(DEBUG_TAG,"IOException");
}
}else{
Log.e(DEBUG_TAG,"Url NULL");
}
}
 
private Runnalbe mRunnable = new Runnable(){
 
public void run(){
while(true){
try{
Thread.sleep(5*1000);
mHandler.sendMessage(mHandler.obtainMessage());
}catch(InterruptedException e){
Log.e(DEBUG_TAG,e.toString());
}
}
}
};
 
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
refresh();
}
};
}


 

Socket通信(套件字)

端口号最好大于1023,否和可能跟默认的其他服务端口号冲突。

例:服务器

public class Server implements Runnable{
public void run(){
try{
//创建ServerSocket
ServerSocket serverSock = new ServerSocket(54321);
while(true){
//等待接收客户端的请求
Socket client = serverSocket.accept();
System.out.println("accept");
try{
//接收客户端的消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = in.readLine();
//向服务器发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
out.println("server message");
//关闭流
in.close();
out.close();
 
}catch(Exception e){
e.printStackTrance();
}finally{
client.close();
}
}
}catch(Exception e){
e.printStackTrance();
}
}
 
//开启服务器
public static void main(String[] a){
Thread desktopServerThread = new Thread(new Server());
desktopServerThread.start();
}
}
 


例:客户端

public class Activity01 extends Activity{
private final String DEBUG_TAG = "Activity01";
 
private TextView mTextView = null;
private EditText mEditText = null;
private Button mButton = null;
 
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
 
mButton = (Button)findViewById(R.id.BUtton01);
mTextView = (TextView)findViewById(R.id.TextView01);
mEditText = (EditText)findViewById(R.id.EditText01);
 
//登录
mButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Socket socket = null;
String message = mEditText.getText().toString()+"\r\n";
try{
//创建Socket
socket = new Socket("192.168.1.110",54321);
//向服务器发送消息
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()),true);
out.println(message);
 
//接收来自服务器的消息
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
 
if(msg != null){
mTextView.setText(msg);
}else{
mTextView.setView("数据错误!");
}
 
//关闭流
out.close();
br.close();
socket.close();
 
}catch(Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
});
}
}


 

例:聊天工具

服务器

public class Server{
private static final int SERVERPORT = 54321;
//客户端连接
private static List<Socket> mClientList = new ArrayList<Socket>();
//线程池
private ExecutorService mExcutorService;
private ServierSocket mServerSocket;
 
public static void main(String[] args){
new Socket();
}
 
public Socket(){
try{
//设置服务端口
mServerSocket = new ServerSocket(SERVERPORT);
mExcutorService = Excutors.newCachedThreadPool();
 
//设置临时存放客户端连接的对象
Socket client = null;
while(true){
//接收客户端连接并添加到list中
client = mServiceSocket.accept();
mClientList.add(client);
//开启一个客户端的线程
mExecutorService.execute(new ThreadServer(client));
}
}catch(IOException e){
e.printStackTrace();
}
}
 
//每个客户端一个线程
static class ThreadServer implements Runnable{
private Socket mSocket;
private BufferedReader mBufferedReader;
private PrintWriter mPrintWriter;
private String mStrMSG;
 
public ThreadServer(Socket socket) throws IOException{
this.mSocket = socket;
mBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
mStrMSG = "user:"+this.mSocket.getInetAddresss()+"come total:"+mClientList.size();
sendMessage();
}
 
public void run(){
try{
while((mStrMSG = mBufferedReader.readLine()!=null){
if(mStrMSG.trim().equals("exit")){
//当一个客户端退书
mClientList.remove(mSocket);
mBufferedReader.close();
mPrintWriter.close();
sendMessage();
break;
}else{
mStrMSG = mSocket.getInetAddress()+":"+mStrMSG;
sendMessage();
}
}
}catch(IOException e){
e.printStackTrace();
}
 
private void sendMessage() throws IOException{
System.out.println(mStrMSG);
for(Scoket client : mClientList){
mPrintWirter = new PrintWriter(client.getOutputStream(),true);
mPrintWriter.println(mStrMSG);
}
}
}
}
 
}


 

客户端

public class Activity01 extends Activity{
private final String DEBUG_TAG = "Activity01";
 
private static final String SERVERIP = "192,168.1.110";
private static final int SERVERPORT = 54321;
private Thread mThread = null;
private Socket mSocket = null;
private Button mButton_In = null;
private EditText mEditText01 = null;
private EditText mEditText02 = null;
private BufferedReader mBufferedReader = null;
private PrintWriter mPrintWriter = null;
private String mStrMSG = "";
 
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mButton_in = (Button)findViewById(R.id.Button_In);
mButton_Send = (Button)findViewById(R.id.Button_Send);
mEditText01 = (EditText)findViewById(R.id.EditText01);
mEditText02 = (EditText)findViewById(R.id.EditText02);
 
//登录
mButton_In.setOnClickListener(new OnClickListener(){
public void onClick(View v){
try{
mSocket = new Socket(SERVERIP,SERVERPORT);
mBufferedReader = new BufferedReader(new InputStreamReader(mSocket.getOutputStream()));
mPrintWriter = new PrintWriter(mSocket.getOutputStream(),true);
}catch(Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
});
//发送消息
mButtuon_Send.setOnClickListener(new OnClickListener()){
public void onClick(View v){
try{
//取得编辑框中输入的尼日个噢你
String str = mEditext02.getText().toString()+"\n";
//发送给服务器
mPrintWriter.print(str);
mPrintWriter.flush();
 
}catch(Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
});
 
mThread = new Thread(mRunnable);
mThread.start();
}
 
//监听无夫妻发来的消息
private Runnable mRunnable = new Runnable(){
public void run(){
while(true){
tyr{
if((mStrMSG = mBufferedReader.readLine()) != null){
//消息换行
mStrMSG += "\n";
mHandler.sendMessage(mHandler.obtainMessage());
}
}catch(Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
}
};
 
Handler mHandler = new Hnadler(){
public void handlerMessage(Message msg){
super.handleMessage(msg);
 
try{
//将聊天记录添加进来
mEditText01.append(mStrMSG);
}catch(Exception e){
Log.e(DEBUG_TAG,e.toString());
}
}
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值