Java学习笔记【十二、网络编程】

原计划的学习结束时间是3月4日,目前看来已经延迟了,距离低标还差一些,多方面原因,也不找借口,利用周末赶赶进度,争取本周末把低标完成吧!

参考:
http://www.runoob.com/java/java-url-processing.html url
http://www.runoob.com/java/java-networking.html 网络编程
http://blog.csdn.net/aitangyong/article/details/49661907 backlog的含义

URL统一资源定位符

  • URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址。表示为互联网上的资源,如网页或者FTP地址。
  • URL的格式:protocol://host:port/path?query#fragment
  • 例如:http://www.runoob.com/index.html?language=cn#j2se
    URL 解析:
    协议为(protocol):http
    主机为(host:port):www.runoob.com
    端口号为(port): 80 ,以上URL实例并未指定端口,因为 HTTP 协议默认的端口号为 80。
    文件路径为(path):/index.html
    请求参数(query):language=cn
    定位位置(fragment):j2se,定位到网页中 id 属性为 j2se 的 HTML 元素位置 。

URL类方法

  • 构造
    URL(String protocol,String host,String port,String file)
    URL(String protocol,String host,String file) 使用默认端口
    URL(String url) 直接用字符串构造
    URL(String context,String url) 使用基地址和相对URL构造

  • 方法
    getXXX() 如getHost()获取host,getPort()获取端口,getDefaultPort()获取默认端口
    public URLConnection openConnection() throws IOException 打开一个URL连接,并运行客户端访问资源

URLConnection 方法

public InputStream getInputStream() throws IOException 返回URL的输入流,用于读取资源
public OutputStream getOutputStream() throws IOException 返回URL的输出流, 用于写入资源

    public class ConnectionDemo {

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	try {
		URL url = new URL("http://www.baidu.com/");
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection con = urlConnection instanceof HttpURLConnection ? (HttpURLConnection) urlConnection
				: null;
		String urlString = "";
		if (null != con) {
			InputStream in = con.getInputStream();
			InputStreamReader isr = new InputStreamReader(in);
			BufferedReader br = new BufferedReader(isr);
			String current;
			while ((current = br.readLine()) != null) {
				urlString += current;
			}
		}
		System.out.println(urlString);
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

    }

    }

Socket编程

套接字使用TCP提供了两台计算机之间的通信机制。 客户端程序创建一个套接字,并尝试连接服务器的套接字。
当连接建立时,服务器会创建一个 Socket 对象。客户端和服务器现在可以通过对 Socket 对象的写入和读取来进行进行通信。
java.net.Socket 类代表一个套接字,并且 java.net.ServerSocket 类为服务器程序提供了一种来监听客户端,并与他们建立连接的机制。
以下步骤在两台计算机之间使用套接字建立TCP连接时会出现:
服务器实例化一个 ServerSocket 对象,表示通过服务器上的端口通信。
服务器调用 ServerSocket 类的 accept() 方法,该方法将一直等待,直到客户端连接到服务器上给定的端口。
服务器正在等待时,一个客户端实例化一个 Socket 对象,指定服务器名称和端口号来请求连接。
Socket 类的构造函数试图将客户端连接到指定的服务器和端口号。如果通信被建立,则在客户端创建一个 Socket 对象能够与服务器进行通信。
在服务器端,accept() 方法返回服务器上一个新的 socket 引用,该 socket 连接到客户端的 socket。
连接建立后,通过使用 I/O 流在进行通信,每一个socket都有一个输出流和一个输入流,客户端的输出流连接到服务器端的输入流,而客户端的输入流连接到服务器端的输出流。
TCP 是一个双向的通信协议,因此数据可以通过两个数据流在同一时间发送.以下是一些类提供的一套完整的有用的方法来实现 socket。

ServerSocket类

服务器端的用来侦听客户端请求的类

  • 构造
    public ServerSocket(int port) throws IOException
    创建绑定到特定端口的服务器套接字。
    public ServerSocket(int port, int backlog) throws IOException
    利用指定的 backlog 创建服务器套接字并将其绑定到指定的本地端口号。 ** backlog 指服务器端存放尚未处理的客户端socket的容量 **
    public ServerSocket(int port, int backlog, InetAddress address) throws IOException
    使用指定的端口、侦听 backlog 和要绑定到的本地 IP 地址创建服务器。
    public ServerSocket() throws IOException
    创建非绑定服务器套接字。

  • 方法
    public int getLocalPort()
    返回此套接字在其上侦听的端口。
    public Socket accept() throws IOException
    侦听并接受到此套接字的连接。
    public void setSoTimeout(int timeout)
    通过指定超时值启用/禁用 SO_TIMEOUT,以毫秒为单位。
    public void bind(SocketAddress host, int backlog)
    将 ServerSocket 绑定到特定地址(IP 地址和端口号)。

Socket类

客户端使用的用来和服务器端通信的套接字类。客户端要获取一个 Socket 对象通过实例化 ,而 服务器获得一个 Socket 对象则通过 accept() 方法的返回值。

  • 构造
    public Socket(String host, int port) throws UnknownHostException, IOException.
    创建一个流套接字并将其连接到指定主机上的指定端口号。
    public Socket(InetAddress host, int port) throws IOException
    创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
    public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
    创建一个套接字并将其连接到指定远程主机上的指定远程端口。
    public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException.
    创建一个套接字并将其连接到指定远程地址上的指定远程端口。
    public Socket()
    通过系统默认类型的 SocketImpl 创建未连接套接字
  • 方法
    1 public void connect(SocketAddress host, int timeout) throws IOException
    将此套接字连接到服务器,并指定一个超时值。
    2 public InetAddress getInetAddress()
    返回套接字连接的地址。
    3 public int getPort()
    返回此套接字连接到的远程端口。
    4 public int getLocalPort()
    返回此套接字绑定到的本地端口。
    5 public SocketAddress getRemoteSocketAddress()
    返回此套接字连接的端点的地址,如果未连接则返回 null。
    6 public InputStream getInputStream() throws IOException
    返回此套接字的输入流。
    7 public OutputStream getOutputStream() throws IOException
    返回此套接字的输出流。
    8 public void close() throws IOException
    关闭此套接字。

服务器端Demo:

    public class ServerDemo {

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	try {
		ServerSocket serverSocket = new ServerSocket(6666,5);//backlog 最多缓冲5个客户端请求,超出的拒绝访问
		serverSocket.setSoTimeout(10000);//10s超时
		while(true){
			//侦听,获取一个套接字
			Socket server = serverSocket.accept();
			//获取该套接字的输入流,从此输入流可获取客户端的数据
			InputStream in = server.getInputStream();
			DataInputStream dataIn = new DataInputStream(in);
			System.out.println(dataIn.readUTF());
			//获取输出流,可向客户端写数据
			OutputStream out = server.getOutputStream();
			DataOutputStream dataOut = new DataOutputStream(out);
			dataOut.writeUTF("Thanks for connect!");
			//假装处理需要1s钟
			Thread.sleep(1000);
			//通讯完毕要关闭套接字
			server.close();
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }

    }

客户端Demo:

    public class ClientDemo extends Thread{

    public static void main(String[] args) {
	// TODO Auto-generated method stub
	for(int i=0;i<10;i++){
		Thread t = new ClientDemo();
		t.start();
	}
    }
    public void run(){

	try {
		//创建一个套接字,同时连接到制定的ip和端口
		Socket client = new Socket("localhost",6666);
		//获取输出流,向服务端写消息
		OutputStream out = client.getOutputStream();
		DataOutputStream dataOut = new DataOutputStream(out);
		dataOut.writeUTF("Hello! Server!");
		//获取输入流,接收服务端的消息
		InputStream in = client.getInputStream();
		DataInputStream dataIn = new DataInputStream(in);
		System.out.println(dataIn.readUTF());
		client.close();
		
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }

    }
原文地址:https://www.cnblogs.com/shanelau/p/6502968.html