相关介绍
实现网络功能要靠URL类、URLConnection类、socket类、DatagramSocket类
- DataInputStream和DataOutputStream(PrintStream)类 是网间数据流的载体。
- URLConnection类提供比URL类更强的与服务器交互的控制功能。
- Socket类适用于面向连接的、可靠性要求高的应用。(分为客户端、服务器端、用TCP协议通信)
- Datagram类适用于效率要求高的应用。(用UDP通信)
- 服务器程序是多线程的,可处理多个用户的请求。
实例分析
1、下面是一个基于TCP通过socket实现client端和server端的通信程序。(类似于简单的聊天程序)
//服务器程序
package oracle.hl.Sockets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Socket编程 服务器程序
* @author Administrator
*
*/
public class SocketMyServer {
public static void main(String args[]){
try{
//建立ServerSocket并等待连接请求
ServerSocket server = new ServerSocket(1700);
Socket socket = server.accept();
//连接建立,通过Socket获得连接上的输入\输入流
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream());
//获取标准输入流,从键盘上接收数据
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//先读取Client发送的数据,然后从标准输入读取数据发送给Client
//当接收到bye时关闭连接
String s ;
while(!(s=in.readLine()).equals("bye")){
System.out.println("# Received from Client: "+s);
System.out.print("@ To Client:" );
pw.println(sin.readLine());
pw.flush();
}
System.out.println("The Connection is closing....");
//关闭各种连接
in.close();
pw.close();
socket.close();
server.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
//客户端程序
package oracle.hl.Sockets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Socket客户端程序
* @author Administrator
*/
public class SocketMyClient {
public static void main(String[] args) {
try {
System.out.println("client is runing:");
Socket socket = new Socket("127.0.0.1",1700); //发出连接请求
//建立连接,通过Socket获取连接上的输入\输出流
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//创建标准输入流,从键盘接收数据
BufferedReader sin = new BufferedReader(new InputStreamReader(System.in));
//从标准输入中读取一行数据,发送给Server端,当用户输入bye时结束连接
String s ;
do{
System.out.print("# To Server : ");
s = sin.readLine();
out.println(s);
out.flush();
if(!s.equals("bye")){
System.out.println("@ server response:" + in.readLine());
}else{
System.out.println("The connection is closing");
}
}while(!s.equals("bye"));
//关闭各种连接
out.close();
in.close();
socket.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
测试结果截图:
2、基于UDP协议的网络通信,通过 DatagramSocket类的一个文件传输的小程序
服务器端程序:
package oracle.hl.Sockets;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MyUdpServer {
DatagramSocket socket = null;
BufferedReader br = null;
boolean moreQuotes = true;
public void serverWork()throws IOException{
//创建数据报套接字
socket = new DatagramSocket(5000);
//制定要返回给客户端数据的数据源
br = new BufferedReader(new FileReader("SocketMyClient.java"));
while(moreQuotes){
//构造字节缓冲区
byte [] buf = new byte[256];
//接收客户端程序发过来的数据报
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String dString = null;
if((dString = br.readLine()).equals("bye")){
br.close();
moreQuotes = false;
dString = "no more sentences . Bye";
}
//获取要发送的数据
buf = dString.getBytes();
//记录客户端主机的ip地址、端口号等。
InetAddress address = packet.getAddress();
int port = packet.getPort();
//构造向客户端发送的数据包
packet = new DatagramPacket(buf,buf.length,address,port);
socket.send(packet);
}
socket.close();
}
//服务器端程序入口
public static void main(String args []){
MyUdpServer server = new MyUdpServer();
try{
server.serverWork();
}catch(IOException e){
e.printStackTrace();
}
}
}
客户端程序:
package oracle.hl.Sockets;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class MyUdpClient {
public static void main(String[] args) throws IOException {
boolean flags = true;
//构造数据报Socket
DatagramSocket socket = new DatagramSocket();
//下面是通过名字获取本机的ip地址
InetAddress address = InetAddress.getByName("localhost");
// InetAddress ad = InetAddress.getLocalHost();
// System.out.println(ad);
//构造请求数据包并发送
System.out.println("The sentence by the server :\n");
while(flags){
byte[] buf= new byte[256];
//发送空数据报给服务器
DatagramPacket packet = new DatagramPacket(buf,buf.length,address,5000);
socket.send(packet);
//构造接受数据报并启动接受
packet = new DatagramPacket(buf,buf.length);
socket.receive(packet);
//受到Server端响应数据报,获取数据并显示。
String received = new String(packet.getData());
if(received.equals("no more sentences . Bye")) flags = false;
System.out.println(received);
}
//关闭数据报
socket.close();
}
}