Java网络通信基础编程
一、同步阻塞方式(BIO)
方式一:
服务器端(Server):
package com.ietree.basicskill.socket.mode1; import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket; /**
* 服务端
*/
public class Server {
// 端口号
final static int PORT = 8765;
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(PORT);
System.out.println("Server start......");
// 进行阻塞
Socket socket = server.accept();
// 创建一个程序执行客户端的任务
new Thread(new ServerHandler(socket)).start(); } catch (IOException e) {
e.printStackTrace();
} finally {
if(server != null){
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
server = null;
}
}
}
采用多线程来处理接收到的请求(ServerHandler):
package com.ietree.basicskill.socket.mode1; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket; public class ServerHandler implements Runnable {
private Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
} @Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
String body = null;
while (true) {
body = in.readLine();
if(body == null){
break;
}
System.out.println("Server: " + body);
out.println("服务器端回送响应的数据。");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket = null;
}
}
}
客户端(Client):
package com.ietree.basicskill.socket.mode1; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket; /**
* 客户端
*/
public class Client {
final static String ADDRESS = "127.0.0.1";
final static int PORT = 8765;
public static void main(String[] args) {
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socket = new Socket(ADDRESS, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true); // 向服务器端发送数据
out.println("接收到客户端的请求数据......");
String response = in.readLine();
System.out.println("Client: " + response);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out != null){
try {
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
socket = null;
}
}
}
程序输出:
Server:
Server start......
Server: 接收到客户端的请求数据......
Client:
Client: 服务器端回送响应的数据。
方式二:
Server类:
package com.ietree.basicskill.socket.basic.bio2; import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket; /**
* Created by Administrator on 2017/5/25.
*/
public class Server {
final static int PORT = 8765; public static void main(String[] args) {
ServerSocket server = null;
BufferedReader in = null;
PrintWriter out = null;
try {
server = new ServerSocket(PORT);
System.out.println("Server Start......");
Socket socket = null;
HandlerExecutorPool executorPool = new HandlerExecutorPool(50, 1000);
while (true) {
socket = server.accept();
executorPool.execute(new ServerHandler(socket));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (server != null) {
try {
server.close();
} catch (Exception e3) {
e3.printStackTrace();
}
}
server = null;
}
}
}
serverHandler类:
package com.ietree.basicskill.socket.basic.bio2; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket; /**
* Created by Administrator on 2017/5/25.
*/
public class ServerHandler implements Runnable {
private Socket socket; public ServerHandler(Socket socket) {
this.socket = socket;
} @Override
public void run() {
BufferedReader in = null;
PrintWriter out = null;
try {
try {
in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
String body = null;
while (true) {
body = in.readLine();
if (body == null) {
System.out.println("Server:" + body);
out.println("Server Response");
}
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (Exception e3) {
e3.printStackTrace();
}
}
socket = null;
}
}
}
线程池HandlerExecutorPool类:
package com.ietree.basicskill.socket.basic.bio2; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; /**
* Created by Administrator on 2017/5/25.
*/
public class HandlerExecutorPool { private ExecutorService executor; public HandlerExecutorPool(int maxPoolSize, int queueSize) {
this.executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(),
maxPoolSize,
120L,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(queueSize)
);
} public void execute(Runnable task) {
executor.execute(task);
}
}
客户端Client类:
package com.ietree.basicskill.socket.basic.bio2; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket; /**
* Created by Administrator on 2017/5/25.
*/
public class Client { final static String ADDRESS = "127.0.0.1";
final static int PORT = 8765; public static void main(String[] args) {
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socket = new Socket(ADDRESS, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("Client request");
String response = in.readLine();
System.out.println("Client:" + response);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (Exception e3) {
e3.printStackTrace();
}
}
socket = null;
}
}
}
程序输出:
Server端:
Server Start......
Server:Client request
Client端:
Client:Server Response
二、 同步非阻塞(NIO)
三、异步非阻塞(AIO)
Java网络通信基础编程的更多相关文章
- Java网络多线程编程:对象流错误导致Connection reset
Java网络多线程编程--对象流错误导致Connection reset 在老韩的网络多线程编程实战项目中,发生了如下报错: 服务器端和客户端均发生了报错,在确定相应对象流代码完全没有问题之后,回归定 ...
- (转)Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
原文出自:http://blog.csdn.net/anxpp/article/details/51512200 1.BIO编程 1.1.传统的BIO编程 网络编程的基本模型是C/S模型,即两个进程间 ...
- Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码)
本文会从传统的BIO到NIO再到AIO自浅至深介绍,并附上完整的代码讲解. 下面代码中会使用这样一个例子:客户端发送一段算式的字符串到服务器,服务器计算后返回结果到客户端. 代码的所有说明,都直接作为 ...
- Java 网络IO编程(BIO、NIO、AIO)
本概念 BIO编程 传统的BIO编程 代码示例: public class Server { final static int PROT = 8765; public static void main ...
- 如何使用socket进行java网络编程(三)
本篇文章继续记录java网络通讯编程的学习.在本系列笔记的第一篇中曾经记录过一个项目中的程序,当时还处于项目早期,还未进入与第三方公司的联调阶段,笔者只是用java写了一个client程序模拟了一下第 ...
- 20145205 《Java程序设计》实验报告五:Java网络编程及安全
20145205 <Java程序设计>实验报告五:Java网络编程及安全 实验要求 1.掌握Socket程序的编写: 2.掌握密码技术的使用: 3.客户端中输入明文,利用DES算法加密,D ...
- Java 网络编程学习总结
新手一枚,Java学习中,把自己学习网络编程的知识总结一下,梳理下知识,方便日后查阅,高手莫进. 本文的主要内容: [1] 网络编程认识 [2] TCP/IP编程 ...
- 20145212 实验五《Java网络编程》
20145212 实验五<Java网络编程> 一.实验内容 1.运行下载的TCP代码,结对进行,一人服务器,一人客户端: 2.利用加解密代码包,编译运行代码,一人加密,一人解密: 3.集成 ...
- 20145213《Java程序设计》实验五Java网络编程及安全
20145213<Java程序设计>实验五Java网络编程及安全 实验内容 1.掌握Socket程序的编写. 2.掌握密码技术的使用. 3.设计安全传输系统. 实验预期 1.客户端与服务器 ...
随机推荐
- Vim快捷键操作命令大全
Vim是一个超牛的编辑器,命令功能十分强大 .而且这些命令大都可以进行组合 ,比如,9yy命令表示复制9行内容,9表示要复制的行数,同样100dd表示删除100行,当数字和命令合作的时候,就比 ...
- ThinkPHP 的URL重写时遇到No input file specified的解决方法
因为在Fastcgi模式下,php不支持rewrite的目标网址的PATH_INFO的解析 ThinkPHP运行在URL_MODEL=2时,会出现 No input file specified.的情 ...
- mysql --mysqli::multi_query 和 mysqli_multi_query
语法: 对象化:bool mysqli::multi_query ( string $query ) 过程化:bool mysqli_multi_query ( mysqli $link , stri ...
- 360破解大赛crackme分析--之3DES解密附加数据
具体的分析这里有.本人仅仅是对这里面有趣的算法进行了一些学习 分析链接 这次是逆向的使用3DES解密的过程中的内容: 使用微软的crypt库 使用3DES解密程序中的附加数据 代码: VOID enc ...
- [WPF]实现密码框的密码绑定
正如绑定TextBox控件的Text属性一样, 我们希望能够将PasswordBox空间的Password属性进行绑定, 比如在MVVM模式中,这似乎是必须的, 但可惜的是, Password属性是不 ...
- CSS顶级技巧大放送,div+css布局必知
字体大小使用px 在一行内声明CSS 对比下面两个: h2 {font-size:18px; border:1px solid blue; color:#000; } h2 { font-siz ...
- python3----练习题(图片转字符画)
import argparse from PIL import Image def parse_param(): parser = argparse.ArgumentParser() # 命令行输入参 ...
- A mail sent to Google chromium.org Groups for Help
Hi, I've ported Chromium M39 to 4.4 using WebView. The main modifications are: I changed AwContents: ...
- redis的简单操作
今天在代码中使用hset存入redis中:jedis.hset(key.getBytes(), field.getBytes(), ObjectInfoPojo); 需要在redis中去验证数据是否存 ...
- 高级service之ipc ADIL用法
感谢 如果你还没有看过前面一篇文章,建议先去阅读一下 Android Service完全解析,关于服务你所需知道的一切(上) ,因为本篇文章中涉及到的代码是在上篇文章的基础上进行修改的. 在上篇文章中 ...