Skip to content

Commit 8d162e8

Browse files
author
孟祥程
committed
网络编程
1 parent 88dc346 commit 8d162e8

13 files changed

Lines changed: 841 additions & 0 deletions
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.msj.network.aio;
2+
3+
import java.io.UnsupportedEncodingException;
4+
import java.net.InetSocketAddress;
5+
import java.nio.ByteBuffer;
6+
import java.nio.channels.AsynchronousSocketChannel;
7+
import java.util.concurrent.ExecutionException;
8+
9+
public class Client implements Runnable{
10+
11+
private AsynchronousSocketChannel asc ;
12+
13+
public Client() throws Exception {
14+
asc = AsynchronousSocketChannel.open();
15+
}
16+
17+
public void connect(){
18+
asc.connect(new InetSocketAddress("127.0.0.1", 8765));
19+
}
20+
21+
public void write(String request){
22+
try {
23+
asc.write(ByteBuffer.wrap(request.getBytes())).get();
24+
read();
25+
} catch (Exception e) {
26+
e.printStackTrace();
27+
}
28+
}
29+
30+
private void read() {
31+
ByteBuffer buf = ByteBuffer.allocate(1024);
32+
try {
33+
asc.read(buf).get();
34+
buf.flip();
35+
byte[] respByte = new byte[buf.remaining()];
36+
buf.get(respByte);
37+
System.out.println(new String(respByte,"utf-8").trim());
38+
} catch (InterruptedException e) {
39+
e.printStackTrace();
40+
} catch (ExecutionException e) {
41+
e.printStackTrace();
42+
} catch (UnsupportedEncodingException e) {
43+
e.printStackTrace();
44+
}
45+
}
46+
47+
@Override
48+
public void run() {
49+
while(true){
50+
51+
}
52+
}
53+
54+
public static void main(String[] args) throws Exception {
55+
Client c1 = new Client();
56+
c1.connect();
57+
58+
Client c2 = new Client();
59+
c2.connect();
60+
61+
Client c3 = new Client();
62+
c3.connect();
63+
64+
new Thread(c1, "c1").start();
65+
new Thread(c2, "c2").start();
66+
new Thread(c3, "c3").start();
67+
68+
Thread.sleep(1000);
69+
70+
c1.write("c1 aaa");
71+
c2.write("c2 bbbb");
72+
c3.write("c3 ccccc");
73+
}
74+
75+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.msj.network.aio;
2+
3+
import java.net.InetSocketAddress;
4+
import java.nio.channels.AsynchronousChannelGroup;
5+
import java.nio.channels.AsynchronousServerSocketChannel;
6+
import java.util.concurrent.ExecutorService;
7+
import java.util.concurrent.Executors;
8+
9+
public class Server {
10+
//线程池
11+
private ExecutorService executorService;
12+
//线程组
13+
private AsynchronousChannelGroup threadGroup;
14+
//服务器通道
15+
public AsynchronousServerSocketChannel assc;
16+
17+
public Server(int port){
18+
try {
19+
//创建一个缓存池
20+
executorService = Executors.newCachedThreadPool();
21+
//创建线程组
22+
threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
23+
//创建服务器通道
24+
assc = AsynchronousServerSocketChannel.open(threadGroup);
25+
//进行绑定
26+
assc.bind(new InetSocketAddress(port));
27+
28+
System.out.println("server start , port : " + port);
29+
//进行阻塞
30+
assc.accept(this, new ServerCompletionHandler());
31+
//一直阻塞 不让服务器停止
32+
Thread.sleep(Integer.MAX_VALUE);
33+
34+
} catch (Exception e) {
35+
e.printStackTrace();
36+
}
37+
}
38+
39+
public static void main(String[] args) {
40+
Server server = new Server(8765);
41+
}
42+
43+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.msj.network.aio;
2+
3+
import java.nio.ByteBuffer;
4+
import java.nio.channels.AsynchronousSocketChannel;
5+
import java.nio.channels.CompletionHandler;
6+
import java.util.concurrent.ExecutionException;
7+
8+
public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {
9+
10+
@Override
11+
public void completed(AsynchronousSocketChannel asc, Server attachment) {
12+
//当有下一个客户端接入的时候 直接调用Server的accept方法,这样反复执行下去,保证多个客户端都可以阻塞
13+
attachment.assc.accept(attachment, this);
14+
read(asc);
15+
}
16+
17+
private void read(final AsynchronousSocketChannel asc) {
18+
//读取数据
19+
ByteBuffer buf = ByteBuffer.allocate(1024);
20+
asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() {
21+
@Override
22+
public void completed(Integer resultSize, ByteBuffer attachment) {
23+
//进行读取之后,重置标识位
24+
attachment.flip();
25+
//获得读取的字节数
26+
System.out.println("Server -> " + "收到客户端的数据长度为:" + resultSize);
27+
//获取读取的数据
28+
String resultData = new String(attachment.array()).trim();
29+
System.out.println("Server -> " + "收到客户端的数据信息为:" + resultData);
30+
String response = "服务器响应, 收到了客户端发来的数据: " + resultData;
31+
write(asc, response);
32+
}
33+
@Override
34+
public void failed(Throwable exc, ByteBuffer attachment) {
35+
exc.printStackTrace();
36+
}
37+
});
38+
}
39+
40+
private void write(AsynchronousSocketChannel asc, String response) {
41+
try {
42+
ByteBuffer buf = ByteBuffer.allocate(1024);
43+
buf.put(response.getBytes());
44+
buf.flip();
45+
asc.write(buf).get();
46+
} catch (InterruptedException e) {
47+
e.printStackTrace();
48+
} catch (ExecutionException e) {
49+
e.printStackTrace();
50+
}
51+
}
52+
53+
@Override
54+
public void failed(Throwable exc, Server attachment) {
55+
exc.printStackTrace();
56+
}
57+
58+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.msj.network.bio;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.Socket;
8+
9+
/**
10+
* @author Vincent.M mengshaojie@188.com
11+
* @date 2017/3/20 下午4:41
12+
* @copyright ©2017 孟少杰 All Rights Reserved
13+
* @desc 传统BIO编程,客户端
14+
*/
15+
public class Client {
16+
17+
final static String ADDRESS = "127.0.0.1";
18+
final static int PORT = 8765;
19+
20+
public static void main(String[] args) {
21+
22+
Socket socket = null;
23+
BufferedReader in = null;
24+
PrintWriter out = null;
25+
26+
try {
27+
socket = new Socket(ADDRESS, PORT);
28+
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
29+
out = new PrintWriter(socket.getOutputStream(), true);
30+
31+
//向服务器端发送数据
32+
out.println("接收到客户端的请求数据...");
33+
out.println("接收到客户端的请求数据1111...");
34+
String response = in.readLine();
35+
System.out.println("Client: " + response);
36+
37+
} catch (Exception e) {
38+
e.printStackTrace();
39+
} finally {
40+
if(in != null){
41+
try {
42+
in.close();
43+
} catch (IOException e) {
44+
e.printStackTrace();
45+
}
46+
}
47+
if(out != null){
48+
try {
49+
out.close();
50+
} catch (Exception e) {
51+
e.printStackTrace();
52+
}
53+
}
54+
if(socket != null){
55+
try {
56+
socket.close();
57+
} catch (IOException e) {
58+
e.printStackTrace();
59+
}
60+
}
61+
socket = null;
62+
}
63+
}
64+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.msj.network.bio;
2+
3+
import java.io.IOException;
4+
import java.net.ServerSocket;
5+
import java.net.Socket;
6+
7+
/**
8+
* @author Vincent.M mengshaojie@188.com
9+
* @date 2017/3/20 下午4:41
10+
* @copyright ©2017 孟少杰 All Rights Reserved
11+
* @desc 传统BIO编程,服务端
12+
*/
13+
public class Server {
14+
15+
final static int PROT = 8765;
16+
17+
public static void main(String[] args) {
18+
19+
ServerSocket server = null;
20+
try {
21+
server = new ServerSocket(PROT);
22+
System.out.println(" server start .. ");
23+
//进行阻塞
24+
Socket socket = server.accept();
25+
//新建一个线程执行客户端的任务
26+
new Thread(new ServerHandler(socket)).start();
27+
28+
} catch (Exception e) {
29+
e.printStackTrace();
30+
} finally {
31+
if(server != null){
32+
try {
33+
server.close();
34+
} catch (IOException e) {
35+
e.printStackTrace();
36+
}
37+
}
38+
server = null;
39+
}
40+
41+
42+
43+
}
44+
45+
46+
47+
48+
49+
50+
51+
52+
53+
54+
55+
56+
57+
58+
59+
60+
61+
62+
63+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.msj.network.bio;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.io.PrintWriter;
7+
import java.net.Socket;
8+
9+
/**
10+
* @author Vincent.M mengshaojie@188.com
11+
* @date 2017/3/20 下午4:41
12+
* @copyright ©2017 孟少杰 All Rights Reserved
13+
* @desc 传统BIO编程
14+
*/
15+
public class ServerHandler implements Runnable{
16+
17+
private Socket socket ;
18+
19+
public ServerHandler(Socket socket){
20+
this.socket = socket;
21+
}
22+
23+
@Override
24+
public void run() {
25+
BufferedReader in = null;
26+
PrintWriter out = null;
27+
try {
28+
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
29+
out = new PrintWriter(this.socket.getOutputStream(), true);
30+
String body = null;
31+
while(true){
32+
body = in.readLine();
33+
if(body == null) break;
34+
System.out.println("Server :" + body);
35+
out.println("服务器端回送响的应数据.");
36+
}
37+
38+
} catch (Exception e) {
39+
e.printStackTrace();
40+
} finally {
41+
if(in != null){
42+
try {
43+
in.close();
44+
} catch (IOException e) {
45+
e.printStackTrace();
46+
}
47+
}
48+
if(out != null){
49+
try {
50+
out.close();
51+
} catch (Exception e) {
52+
e.printStackTrace();
53+
}
54+
}
55+
if(socket != null){
56+
try {
57+
socket.close();
58+
} catch (IOException e) {
59+
e.printStackTrace();
60+
}
61+
}
62+
socket = null;
63+
}
64+
65+
66+
}
67+
68+
}

0 commit comments

Comments
 (0)