Java网络通信

网络通信
1、协议:TCP/IP、UPD/IP、Multicast

2、IO
2.1、同步IO
2.1.1、BIO(Blocking IO):阻塞方式
2.1.2、NIO(Non-Blocking IO):非阻塞方式,Reactor模式(不要打电话给我们,我们会打电话通知你)
Reactor Pattern: http://blog.csdn.net/success041000/article/details/6725110

2.2、异步IO
2.2.1、AIO(Asynchronous IO):Proactor模式

Java Socket编程
1、TCP/IP+BIO 客户端专用一个Socket,资源分配有问题
Server端代码
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerDemo {
	
	public static void main(String[] args) throws IOException{
		int port=9527;//端口
		//1、创建ServerSocket
		ServerSocket server = new ServerSocket(port);
		//2、接收客户端请求:客户端没有请求之前,一直等待
		Socket socket = server.accept();
		//3、读取客户端的数据
		InputStream input = socket.getInputStream();//获取输入
		BufferedReader reader = new BufferedReader(new InputStreamReader(input));
		String received = reader.readLine();
		//4、响应客户端
		OutputStream output = socket.getOutputStream();//返回数据给客户端
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
		if(received != null){
			writer.write("Response " + received);
		}else{
			writer.write("Response is null");
		}
		writer.flush();
		//5、关闭资源
		reader.close();
		writer.close();
		server.close();
	}

}


Client端代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientDemo {
	
	public static void main(String[] args) throws UnknownHostException, IOException{
		//1、创建socket连接
		String host="127.0.0.1";
		int port=9527;
		Socket socket = new Socket(host,port);
		//2、往服务器发送信息
		PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
		out.println("Hello!");
		//3、获取服务器返回的信息
		BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		System.out.println(in.readLine());
		//4、关闭资源
		out.close();
		in.close();
		socket.close();
	}
}


运行的结果为:Response Hello!

2、TCP/IP+NIO 非阻塞方式
Server端代码
 

Clinet端代码

                            

你可能感兴趣的:(java)