(三十三)Java Socket是什么

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiangshangchunjiezi/article/details/87890342

TCP:socket、ServerSocket:https://blog.csdn.net/jiangshangchunjiezi/article/details/76268429

网络上的两个程序通过一个双向的通信连接实现数据的交换,这个双向链路的一端称为Socket。Socket也称为套接字,可以用来实现不同虚拟机或者不同计算机之间的通信。

①在java语言中,Socket分为两种类型:面向连接的Socket通信协议(TCP)和面向无连接的Socket协议(UDP)。

②任何一个Socket都是由IP地址和端口号唯一确定的。

基于TCP的通信过程如下:

首先,Server(服务器)端Listen(监听)指定的某个端口(建议超过1024的端口)是否有连接请求

其次,Client(客户)端向Server端发出Connect(连接)请求;

最后,Server端向Client端发回Accept(接受)消息。

Socket的生命周期可以分为3个阶段:

打开Socket、使用Socket收发数据、关闭Socket

//客户端
public static void main(String[] args) {
		Socket s=null;
		OutputStream os=null;
		InputStream in=null;
		try{
		s=new Socket("192.168.0.105",10006);
		
		os=s.getOutputStream();
		os.write("我是客户端".getBytes());
		
		byte[] b=new byte[1024];
		in=s.getInputStream();
		int len=in.read(b);
		System.out.println(new String(b,0,len));
		}
		catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				
				os.close();
				in.close();
				s.close();;
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
		}
		
		
		  
	}
public static void main(String[] args)  {
		//建立服务端socket服务,并监听一个端口
        ServerSocket ss=null;
        Socket s=null;
        InputStream in=null;
        OutputStream out=null;
		try {
			//建立服务端socket服务,并监听一个端口
			ss = new ServerSocket(10006);
			
			//通过accept方法获取连接过来的客户端对象
			s = ss.accept();
			 String ip=s.getInetAddress().getHostAddress();
	         System.out.println(ip+".........connected");
	         
	         //获取客户端发送过来的数据,通过使用客户端对象的读取流来读取数据
	         in = s.getInputStream();
	         byte[] buf=new byte[1024];
	         int len=0;
	         len = in.read(buf);
	         System.out.println(new String(buf,0,len)+":数据已被接收到");
	         
	         //向客户端发送数据
	         out=s.getOutputStream();
	         out.write("服务器发过来的数据....".getBytes());
	         
	         
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				in.close();
				out.close();
				//s.close();
				
				
			} catch (IOException e) {
				
				e.printStackTrace();
			}
			
		}

       
            
	}

猜你喜欢

转载自blog.csdn.net/jiangshangchunjiezi/article/details/87890342