zoukankan      html  css  js  c++  java
  • Java:Socket通信

        Socket通常也称作"套接字"。用于描写叙述IP地址和port,是一个通信链的句柄。应用程序通常通过"套接字"向网络发出请求或者应答网络请求。

    ServerSocket用于server端,Socket是建立网络连接时使用的。在连接成功时,应用程序两端都会产生一个Socket实例,操作这个实例,完毕所需的会话。

    对于一个网络连接来说,套接字是平等的,并没有区别,不由于在server端或在client而产生不同级别。套接字之间的连接过程能够分为三个步骤:server监听,client请求,连接确认。

    实例一:基于TCP/IP协议的Socket通信一对一:

    package z_test_Socket_Demo;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TestServerSocket {
    
    	public static void main(String[] args) {
    		// TODO 自己主动生成的方法存根
    		ServerSocket serverSocket = null;
    		Socket socket = null;
    		OutputStream outputStream = null;
    		try {
    			serverSocket = new ServerSocket(8888); // 指定监听端口
    			System.out.println("==>> accepting");
    			socket = serverSocket.accept(); // 监听client的请求,方法堵塞,请求成功,返回socket对象
    			outputStream = socket.getOutputStream(); // 获得输出流
    			String string = "==>> Hello client,This is a message from server"; // 随便给client发点东西
    			byte[] buffer = string.getBytes();
    			outputStream.write(buffer);
    			outputStream.flush();
    		} catch (IOException e) {
    			// TODO 自己主动生成的 catch 块
    			e.printStackTrace();
    		} finally {
    			try {
    				serverSocket.close();
    				socket.close();
    				outputStream.close();
    			} catch (IOException e) {
    				// TODO 自己主动生成的 catch 块
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    package z_test_Socket_Demo;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class TestClientSocket {
    
    	public static void main(String[] args) {
    		// TODO 自己主动生成的方法存根
    		Socket socket = null;
    		InputStream inputStream = null;
    		try {
    			// socket = new Socket(InetAddress.getLocalHost(), 8888);
    			// 请求连接服务器的8888端口,构造方法通常能够指定IP地址
    			socket = new Socket("10.25.26.141", 8888);
    			inputStream = socket.getInputStream(); // 获得输入流
    			byte[] buffer = new byte[64];
    			int temp = 0;
    			while ((temp = inputStream.read(buffer)) != -1) { // 将数据读入字节数组,此方法堵塞
    				System.out.println(new String(buffer));
    			}
    		} catch (UnknownHostException e) {
    			// TODO 自己主动生成的 catch 块
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO 自己主动生成的 catch 块
    			e.printStackTrace();
    		} finally {
    			try {
    				socket.close();
    				inputStream.close();
    			} catch (IOException e) {
    				// TODO 自己主动生成的 catch 块
    				e.printStackTrace();
    			}
    		}
    	}
    }
    
    先执行服务器端,打印结果:

    ==>> accepting
    然后执行client,打印结果:

    ==>> Hello client,This is a message from server

    实例二:基于TCP/IP协议的Socket通信一对多:

    仅仅须要把服务器段用一个线程死循环就可以

    package z_test_Socket_Demo;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TestServerSocket {
    
    	public static void main(String[] args) {
    		// TODO 自己主动生成的方法存根
    		new Thread(new ServerThread()).start();
    	}
    
    	private static class ServerThread implements Runnable {
    
    		@Override
    		public void run() {
    			// TODO 自己主动生成的方法存根
    			int i = 1;
    			while (true) {
    				ServerSocket serverSocket = null;
    				Socket socket = null;
    				OutputStream outputStream = null;
    				try {
    					serverSocket = new ServerSocket(8888); // 指定监听端口
    					System.out.println("==>> accepting client" + i++);
    					socket = serverSocket.accept(); // 监听客户端的请求,方法堵塞,请求成功。返回socket对象
    					outputStream = socket.getOutputStream(); // 获得输出流
    					String string = "==>> Hello client" + i++
    							+ ",This is a message from server"; // 随便给客户端发点东西
    					byte[] buffer = string.getBytes();
    					outputStream.write(buffer);
    					outputStream.flush();
    				} catch (IOException e) {
    					// TODO 自己主动生成的 catch 块
    					e.printStackTrace();
    				} finally {
    					try {
    						serverSocket.close();
    						socket.close();
    						outputStream.close();
    					} catch (IOException e) {
    						// TODO 自己主动生成的 catch 块
    						e.printStackTrace();
    					}
    				}
    			}
    		}
    	}
    }
    
    执行服务器段,打印结果:

    ==>> accepting client1

    执行client,client打印结果:

    ==>> Hello client1,This is a message from server

    再次执行client,client打印结果:

    ==>> Hello client2,This is a message from server

    相当于两个不同的client请求连接server


        弄懂的了基于TCP/IP协议的Socket通信,基于其它协议的Socket通信应该能够非常快就能弄明确了。


  • 相关阅读:
    获得插入记录标识号, 鼠标移到DataGrid的行更改颜色(转)
    ESRI ArcGIS 9.0系列软件报价(转)
    世界电子地图
    Microsoft’s.NET MicroFramework初接触
    MapServer初体验成功
    MapScript C# Tutorial Programming MapServer in the ASP .NET Framework(转)
    WPF 中的Width 与 ActualWidth
    可空值类型
    面试时遇到上机编程题
    checked、unchecked
  • 原文地址:https://www.cnblogs.com/lxjshuju/p/6971663.html
Copyright © 2011-2022 走看看