2013.10.28 socket 编程

1,http,socket

Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信。两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客户端向服务器发送请求后,服务器端才能向客户端返回数据。而Socket通信则是在双方建立起连接后就可以直接进行数据的传输,在连接时可实现信息的主动推送,而不需要每次由客户端想服务器发送请求。

socket的分类: 

根据不同的的底层协议,Socket的实现是多样化的。常用的有tcp,udp

socket基本通信模型

2013.10.28 socket 编程_第1张图片


Socket 服务器端实现

package com.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServerTest {
	public static void main(String[] args) {
		
		receiveDataFromClient();
	}
	
	private static void receiveDataFromClient(){
		try {
			ServerSocket ss  = new ServerSocket(124);
			System.out.println("server waiting...");
			Socket socket = ss.accept();
			System.out.println("server got it");
			InputStream is = socket.getInputStream();
			int temp = 0;
			byte[] buffer = new byte[1024];
			while((temp = is.read(buffer)) != -1){
				System.out.println("SocketServer:"+new String(buffer,0,temp));
			}
			
			//如果此时向客户端发一个消息
//			OutputStream os = socket.getOutputStream();
//			os.write(new String("OK".getBytes(),"utf-8").getBytes());
			
			socket.close();
			ss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Socket客户端实现

package com.socket;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SocketClient {
	
	public static void main(String[] args) throws InterruptedException {
		File f = new File("D://"+0+".txt");
		sendToServer(f);
		
//		int i=0;
//		while(i < 3){
//			Thread.sleep(1000);
//			i++;
//		}
	}
	
	private static void sendToServer(File f){
		try {
			InputStream is = new FileInputStream(f);
			Socket socket = new Socket("127.0.0.1", 124);
			OutputStream os = socket.getOutputStream();
			int temp = 0;
			byte[] buffer = new byte[1024];
			while((temp = is.read(buffer)) != -1){
				System.out.println("SocketClient:"+new String(buffer,0,temp));
				os.write(buffer, 0, temp);
			}
			
			//能否接收到服务端发来的消息
//			InputStream is2 = socket.getInputStream();
//			is2.read(buffer);
//			System.out.println("SocketClient received from server:"+new String(buffer,0,temp));
//			if(new String(buffer,0,temp).equals("OK")){
//				System.out.println("SocketClient success");
//			}
			
			socket.close();
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


Android 模拟器中做端口重定向
     开发的过程中遇到一个问题:android的模拟器有个特点,就是访问网络的时候只可以从模拟器主动往出去连。但是却无法主的从外面连接模拟器,这个特点和NAT几乎完全一样,具有单向连接的特性。 实际开发中我们希望模拟器像一台独立的手机一样,能和处于同一局域网中的手机进行端对端的通信。这时就需要做端口重定向。 类似于给路由器做nat的端口重定向。下面几步: >运行模拟器:你会发现模拟器标题 栏上写着端口号:5554,其实这个端口号是模拟器的console端口 >telnet到模拟器的console口上:telnet localhost 5554 (如果你用的是win7. 默认是没有开启telnet功能的,开启的方法看这里 http://hi.baidu.com/lzhts/blog/item/2442d162a0c618cfe6113ae2.html

新建一个Android应用程序作为Socket通信的服务器端。重定向tcp端口:redir add tcp:6661:6661

参考这里:http://blog.csdn.net/itceojingying/article/details/6462682


UDP Server:

package com.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer {
	public static void main(String[] args) {
		receiveData();
	}
	
	private static void receiveData(){
		  // TODO Auto-generated method stub                
        try  
        {  
            //创建一个DatagramSocket对象并指定监听的端口  
            DatagramSocket socket=new DatagramSocket(155);  
            byte[]data=new byte[1024];  
            //创建一个空的DatagramPacket对象用来存放接收到的DatagramPacket  
            DatagramPacket packet=new DatagramPacket(data,data.length);  
            //使用receive方法接收客户端发送的数据  
            
            System.out.println("UDP receiving...");
            socket.receive(packet);      //阻塞的方法。和accept一样。              
            System.out.println("UDP got it");
            String result=new String(packet.getData(),packet.getOffset(),packet.getLength());  
            System.out.println(result);  
        }  
        catch(IOException e)  
        {  
            e.printStackTrace();  
        }  
	}
}

UDP Client

package com.socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

public class UDPClient {
	public static void main(String[] args) {
		sendData();
	}
	
	private static void sendData(){
		try {
			//创建一个DatagramSocket对象  
            DatagramSocket socket=new DatagramSocket();  
            //创建一个表示IP地址的InetAddress对象  
            InetAddress serverAddress=InetAddress.getByName("127.0.0.1");  
            String str="Hello,world!Hello,Everyone!";  
            byte[]data=str.getBytes();  
            //创建一个用于发送的DatagramPacket对象  
            DatagramPacket packet=new DatagramPacket(data,data.length,serverAddress,155);  
            //发送数据  
            socket.send(packet);  
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


你可能感兴趣的:(2013.10.28 socket 编程)