随笔 -- IO -- Socket/ServerSocket -- Echo(BIO)实例
随笔 -- IO -- Socket/ServerSocket -- 系统概述
Java中提供的专门的网络开发程序包------java.net
Java的网络编程提供的两种通信协议:TCP和UDP
19.1 IP与InetAddress
19.1.1 IP地址简介
19.1.2 InetAddress
InetAddress类主要表示IP地址,这个类有两个子类:Inet4Address、Inet6Address。
InetAddress类的常用方法:
⊙ public static InetAddress getByName(String host)throws UnknownHostException :通过主机名称得到InetAddress对象
⊙ public static InetAddress getLocalHost() throws UnknownHostException : 通过本机得到InetAddress对象
⊙ public String getHostName() : 得到IP地址
⊙ public boolean isReachable(int timeout)throws IOException : 判断地址是否可以到达,同时指定超时时间。
package java_.net_.demo.java_15_5; import java.net.InetAddress;
import java.net.UnknownHostException; public class InetAddressMain { public static void main(String[] args) throws Exception { InetAddress locAdd = null;
InetAddress remAdd = null;
locAdd = InetAddress.getLocalHost();
remAdd = InetAddress.getByName("www.baidu.com");
System.out.println("本机名称 :" + locAdd.getHostName());
System.out.println("本机IP地址 :" + locAdd.getHostAddress());
System.out.println("百度IP地址 :" + remAdd);
System.out.println("本机是否可达 :" + locAdd.isReachable(5000));
System.out.println("百度是否可达 :" + remAdd.isReachable(5000));
}
}
19.2 URL与URLConnection
19.2.1 URL
URL统一资源定位符,可以直接使用此类找到互联网上的资源(如一个简单的网页)。
URL类的常用方法:
⊙ public URL(String spec) throws MalformedURLException : 根据指定的地址实例化URL对象。
⊙ public URL(String protocal,String host,int port,String file) throws MalformedURLException : 实例化URL对象,并指定协议、主机、端口名称、资源文件。
⊙ public URLConnection openConnection() throws IOException : 取得一个URLConnection对象。
⊙ public final InputStream openStream() throws IOException : 取得输入流。
package java_.net_.demo.java_15_5.URL_; import java.io.InputStream;
import java.net.URL;
import java.util.Scanner; public class URLMain { public static void main(String[] args) throws Exception{ URL url = new URL("http","www.mldnjava.cn",80,"/curriculum.htm");
InputStream input = url.openStream();
Scanner sc = new Scanner(input);
sc.useDelimiter("\n");
while(sc.hasNext()){
System.out.println(sc.next());
}
}
}
19.2.2 URLConnection
URLConnection是封装访问远程网络资源一般方法的类,通过它可以建立与远程服务器的连接,检查远程资源的一些属性。
此类的常用方法:
⊙ public int getContentLength() : 取得内容的长度。
⊙ public String getContentType() : 取得内容的类型。
⊙ public InputStream getInputStream() throws IOException : 取得连接的输入流。
URLConnection对象可以通过URL实例的openConnection()方法取得。
package java_.net_.demo.java_15_5.URLConnection; import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner; public class URLConnectionMain { public static void main(String[] args) throws Exception{ URL url = new URL("http://www.mldnjava.cn");
URLConnection urlCon = url.openConnection();
System.out.println("内容大小 :" + urlCon.getContentLength());
System.out.println("内容类型 :" + urlCon.getContentType());
InputStream input = urlCon.getInputStream();
Scanner sc = new Scanner(input);
sc.useDelimiter("\n");
while (sc.hasNext()) {
System.out.println(sc.next());
}
}
}
19.3 URLEncoder 与 URLDecoder
在Java中如果要完成编码和解码操作就必须使用URLEncoder 和 URLDecoder两个类。
URLEncoder 可以为传递的内容进行编码;URLDecoder可以为传递的内容进行解码。
URLEncoder类常用的方法:
⊙ public static Spring encode(String s,String enc) throws UnsupportedEncodingException : 使用指定的编码机制将字符串转换为application/x-www-form-urlencoded格式。
URLDecoder类的常用方法:
⊙ public static Spring decode(String s,String enc) throws UnsupportedEncodingException : 使用指定的编码机制对application/x-www-form-urlencoded字符串解码。
package java_.net_.demo.java_15_5.URLEncoder; import java.net.URLDecoder;
import java.net.URLEncoder; public class URLEncoderMain { public static void main(String[] args) throws Exception{ String keyWord = "lime甲骨文";
String encod = URLEncoder.encode(keyWord, "UTF-8");
System.out.println("编码之后的内容 : " + encod);
String decod = URLDecoder.decode(encod, "UTF-8");
System.out.println("解码之后的内容 : " + decod);
}
}
19.4 TCP程序设计
在Java中使用Socket(即套接字)完成TCP程序的开发,使用此类可以方便地简历可靠的、双向的、持续的、点对点的通信连接。
在Socket的程序开发中,服务器端使用ServerSocket等待客户端连接,对于Java的网络程序来讲,每一个客户端都使用Socket对象表示。
19.4.1 ServerSocket 类与 Socket 类
ServerSocket主要用在服务器端程序的开发上,用于接收客户端的连接请求。
ServerSocket类的常用方法:
⊙ public ServerSocket(int port)throws IOException : 创建ServerSocket实例,并指定监听端口。
⊙ public Socket accept() throws IOException : 等待客户端连接,此方法连接之前一直阻塞。
⊙ public InetAddress getInetAddress() : 返回服务器的IP地址。
⊙ public boolean isClosed() : 返回ServerSocket的关闭状态。
⊙ public void close() throws IOException : 关闭ServerSocket。
在服务器端每次运行时都要使用accept()方法等待客户端连接,此方法执行之后服务器端将进入阻塞状态,知道客户端连接之后程序可以向下继续执行。此方法返回值类型是Socket,每一个Socket都表示一个客户端对象。
Socket类的常用方法:
⊙ public Socket(String host,int port) throws UnknownHostException,IOException : 构造Socket对象,同时指定要连接服务器的主机名称及连接端口。
⊙ public InputStream getInputStream() throws IOException : 返回此套接字的输入流。
⊙ public OutputStream getOutputStream() throws IOException : 返回此套接字的输入流。
⊙ public void close() throws IOException : 关闭此Socket。
⊙ public boolean isClosed() : 判断此套接字是否被关闭。
在客户端,程序可以通过Socket类的getInputStream()方法取得服务器的输入信息,在服务器端可以通过getOutputStream()方法取得客户端的输出信息。
19.4.2 第一个TCP程序
Class : ServerSocketMain
package java_.net_.demo.java_15_5.serverSocket; import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date; public class ServerSocketMain { public static void main(String[] args) throws Exception{ ServerSocket server = new ServerSocket(8888);
Socket client = null;
PrintStream out = null;
int count = 1;
while(true){
System.out.println("等待第 " + count + " 个客户端接入");
client = server.accept();
System.out.println("第 " + count + " 个客户端已接入");
count++;
String resp = "Now is : " + new Date();
out = new PrintStream(client.getOutputStream());
out.println(resp);
}
}
}
Class : SocketMain
package java_.net_.demo.java_15_5.socket; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket; public class SocketMain { public static void main(String[] args) throws Exception{
Socket client = new Socket("localhost",8888);
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器端输出内容 :" + str);
client.close();
buf.close();
}
}
19.4.3 案例:Echo程序(BIO)
Echo程序是一个网络编程通信交互的一个经典案例,称为回应程序,即客户端输入那些内容,服务器端会在这些内容前加上“ECHO:”并将信息发回客户端。
本程序中将通过循环的方式使用accept(),这样,每一个客户端执行完毕后,服务器端都可以重新等待用户连接。
Class : EchoServer
package limeNet.server; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket; public class EchoServer { public static void main(String[] args) throws Exception {
ServerSocket server = null;
Socket client = null;
PrintStream out = null;
BufferedReader buf = null;
server = new ServerSocket(8888);
boolean f = true;
while(f){
System.out.println("服务器运行,等待客户端连接。");
client = server.accept();
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag){
String str = buf.readLine();
if(null == str || "".equals(str)){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
out.print("ECHO : " + str);
}
}
}
out.close();
buf.close();
client.close();
}
server.close();
}
}
Class : EchoClient
package limeNet.client; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket; public class EchoClient { public static void main(String[] args) throws Exception, Exception {
Socket client = null;
client = new Socket("localhost",8888);
BufferedReader input = null;
PrintStream out = null;
BufferedReader buf = null;
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(client.getOutputStream());
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean flag = true;
while(flag){
System.out.print("输入信息:");
String str = input.readLine();
out.print(str);
if("bye".equals(str)){
flag = false;
}else{
String echo = buf.readLine();
System.out.println(echo);
}
}
client.close();
buf.close();
}
}
19.4.4 在服务器上应用多线程
对于服务器端来说,如果要加入多线程机制,则应该在每个用户连接之后启动一个新的线程。
Class : EchoThread
package limeNet.thread.server; import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket; public class EchoThread implements Runnable { private Socket accept; public EchoThread() {
super();
}
public EchoThread(Socket accept) {
super();
this.accept = accept;
} public void run() {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(accept.getInputStream());
out = new DataOutputStream(accept.getOutputStream());
boolean goon = true;
while (goon) {
String str = in.readUTF();
if (null == str || "".equals(str)) {
goon = false;
} else {
if ("bye".equalsIgnoreCase(str)) {
goon = false;
} else {
out.writeUTF("ECHO:" + str);
}
}
}
in.close();
out.close();
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Class : EchoThreadServer
package limeNet.thread.server; import java.net.ServerSocket;
import java.net.Socket; public class EchoThreadServer { public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
while(true){
System.out.println("服务器运行,等待客户端连接。");
Socket accept = serverSocket.accept();
new Thread(new EchoThread(accept)).start();
}
}
}
Class : EchoClient
package limeNet.client; import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner; public class EchoClient { public static void main(String[] args) throws Exception, Exception {
Socket client = null;
client = new Socket("localhost",8888);
DataInputStream in = null;
DataOutputStream out = null;
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag){
System.out.print("输入信息:");
String str = sc.nextLine();
out.writeUTF(str);
if("bye".equals(str)){
flag = false;
}else{
String echo = in.readUTF();
System.out.println(echo);
}
}
in.close();
out.close();
sc.close();
client.close();
}
}
19.5 UDP程序设计
19.5.1 UDP简介
19.5.2 UDP程序实现
Class : UDPClient
package limeNet.udp.client; import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket; public class UDPClient { public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(9000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
// 阻塞
ds.receive(dp);
String str = new String(dp.getData(),0,dp.getLength()) + "from " + dp.getAddress().getHostAddress() + " : " + dp.getPort();
System.out.println(str);
ds.close();
}
}
Class : UDPServer
package limeNet.udp.server; import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress; public class UDPServer { public static void main(String[] args) throws IOException {
DatagramSocket ds = null;
DatagramPacket dp = null;
ds = new DatagramSocket(3000);
String str = "Hello World";
dp = new DatagramPacket(str.getBytes(), str.length(),InetAddress.getByName("localhost"),9000);
System.out.println("发送信息。");
ds.send(dp);
ds.close();
}
}
啦啦啦
啦啦啦
啦啦啦
啦啦啦
啦啦啦
啦啦啦
啦啦啦
啦啦啦
随笔 -- IO -- Socket/ServerSocket -- Echo(BIO)实例的更多相关文章
- 随笔 -- IO -- Socket/ServerSocket -- 系统概述
随笔 -- IO -- Socket/ServerSocket -- Echo(BIO)实例 Java 网络编程 网络编程是指编写运行在多个设备(计算机)的程序,这些设备都通过网络连接起来. java ...
- java之TCP(Socket,serverSocket)实例
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...
- Socket网络通信之BIO
Socket网络通信之BIO 如果要让两台计算机实现通信,需要的条件:ip,port,协议. 目前我们用的最多的就是TCP/IP协议和UDP协议.TCP三次握手,所以比较慢,且安全:UDP速度快,但是 ...
- 高级Java工程师必备 ----- 深入分析 Java IO (一)BIO
BIO编程 最原始BIO 网络编程的基本模型是C/S模型,即两个进程间的通信. 服务端提供IP和监听端口,客户端通过连接操作想服务端监听的地址发起连接请求,通过三次握手连接,如果连接成功建立,双方就可 ...
- Flex Socket与Java通信实例说明(转)
Flex Socket与Java通信实例说明(转) 这两天一直在flex的Socket ,现在终于懂了很多.由浅到深一步一步深入.慢慢体会实例,虽然实例都是在网上找的,但也经过了我的测试.我比较喜欢注 ...
- sendEmail报错:at /usr/share/perl5/vendor_perl/IO/Socket/SSL.pm
sendEmail发送邮件是出现以下报错: ******************************************************************* Using the ...
- 简单通过java的socket&serversocket以及多线程技术实现多客户端的数据的传输,并将数据写入hbase中
业务需求说明,由于公司数据中心处于刚开始部署的阶段,这需要涉及其它部分将数据全部汇总到数据中心,这实现的方式是同上传json文件,通过采用socket&serversocket实现传输. 其中 ...
- 网络编程之Socket & ServerSocket
网络编程之Socket & ServerSocket Socket:网络套接字,网络插座,建立网络通信连接至少要一对端口号(socket).socket本质是编程接口(API),对TCP/IP ...
- JAVA SOCKET编程单线程简单实例
服务端: package socketProgram; import java.io.BufferedReader;import java.io.IOException;import java.io. ...
随机推荐
- thymeleaf传值onclick到js
带有单引号 targetUrl('val') <a th:onclick="'javascript:targetUrl(\''+${indexURL.value}+'\');'&quo ...
- JavaScript cookie操作实现点赞功能
JavaScript cookie操作实现点赞功能 参考实现原理,但是代码不够简洁,简洁代码参考:js操作cookie 实现一个点赞功能十分简单,主要问题在于不能重复点赞. 若是一个有用户的网站,可 ...
- 从PCD文件写入和读取点云数据
(1)学习向PCD文件写入点云数据 建立工程文件ch2,然后新建write_pcd.cpp CMakeLists.txt两个文件 write_pcd.cpp : #include <iostr ...
- Eclipse配置方法注释模板
Java-->Code Style-->Code Templates-->Comments
- flush()的原理
输出流类似于一根管道,输出的时候先放到管道里,然后管道满了存到介质上(硬盘或其他地方),当我们输出完后管道里面可能还有剩余,就用flush()清空管道即全部存到介质上.Java默认的缓冲区大小一般是8 ...
- loadrunner 中Error和failed transaction 的区别
Down:没有运行 Pending:挂起 Init:初始化 Ready:准备就绪 Run:正在运行 Rendezvous:正在集结 Passed:运行通过 Failed:运行失败 Error:出现故障 ...
- Linux 套接字与文件描述符
端口和套接字,用于确定指定主机上的哪个本地进程使用了哪个协议和哪台远程主机上的哪个进程进行了通信.端口和套接字的使用可以基于以下几点: ①为每个应用过程分配一个过程标识符(Process ID),每次 ...
- HOW-TO GEEK SCHOOL
This How-To Geek School class is intended for people who want to learn more about security when usin ...
- I2C上拉电阻
在一些PCB的layout中,大家往往会看到在I2C通信的接口处,往往会接入一个4.7K的电阻,有的datasheet上面明确有要求,需要接入,有的则没有要求. I2C接口 对于单片机来讲,有些I ...
- python3 异步模块asyncio
yield方法引入, 这里存在的问题是,如果你想创建从0到1,000,000这样一个很大的序列,你不得不创建能容纳1,000,000个整数的列表. 但是当加入了生成器之后,你可以不用创建完整的序列,你 ...