socket网络编程入门

socket网络编程入门

一、TCP协议

Client

public class Client {
	public static void main(String[] args) throws IOException, IOException {
		//  System.out.println(InetAddress.getLocalHost());
		//  1.连接服务端
		Socket s1 = new Socket(InetAddress.getLocalHost(), 666);	
		//  2.发送数据	
		OutputStream s2 = s1.getOutputStream();//流转换,为了方便输出;注意PrintStream与PrintWriter的区别
		PrintWriter s3 = new PrintWriter(s2);//注意print与println的区别
		s3.println("今晚七点半");
		s3.flush();//如果用PrintWriter的话,必须要刷新(flush)或close(带刷新功能)才能把数据写出去
		//  3.接收数据
		InputStream is = s1.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		System.out.println(br.readLine());
		br.close();//只关最外面一层,相关联的流就全部关闭
		s3.close();//关流原则,先开后关	
	}
}

Server

public class Server {
	public static void main(String[] args) throws IOException {
		//1.创建服务端,指定端口
		ServerSocket s4 = new ServerSocket(666);
		Socket s5 = s4.accept();//监听访问服务端的客户端,一旦有客户端访问就返回一个Socket,没有的话就阻塞在这里。
		//2.接收数据
		InputStream s6 = s5.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(s6));//流转换,为了方便读取
		System.out.println(br.readLine());//readline是读一行,如果用print的话没有换行功能,即没有换行符,所以报错或读不到
		//3.发送数据
		OutputStream os = s5.getOutputStream();//读完之后,获取一个输出流,输出信息。
		PrintWriter pw = new PrintWriter(os);
		pw.println("不约");
    	pw.flush();
	  //pw.close();//服务器端的流一般不关
		br.close();
	}
}

二、UDP协议

Send

public class Send {
	public static void main(String[] args) throws IOException {
	    //1.准备要发送的信息并处理
		String msg = "每天都要进步!";
		byte[] byt = msg.getBytes();
		//2.打包,标明地址
		DatagramPacket dp = new DatagramPacket(byt, byt.length, InetAddress.getLocalHost(), 1231);
		//3.发送
		DatagramSocket ds = new DatagramSocket();
		ds.send(dp);
		ds.close();//关“流”

        //4.接收数据		
//		 byte[] byt2 = new byte[20]; 
//		 DatagramPacket dp2 = new DatagramPacket(byt2, byt2.length);
//		 DatagramSocket ds2 = new DatagramSocket(168);
//		 ds2.receive(dp2);
//		 System.out.println(new String(dp2.getData()));
//		 ds2.close();
		
	}
}

Recieve

public class Recieve {
	public static void main(String[] args) throws IOException {
	    //1.准备接收数据的容器
		byte[] byt = new byte[20]; 
		DatagramPacket dp = new DatagramPacket(byt, byt.length);
		//2.检查端口
		DatagramSocket ds = new DatagramSocket(1231);
		//3.接收数据
		ds.receive(dp);
		System.out.println(new String(dp.getData()));//打印检查
		ds.close();//关“流”
		
		//4.发送数据		  
//		 String msg = "一定要变强!";
//		 byte[] byt2 = msg.getBytes();
//		 DatagramPacket dp2 = new DatagramPacket(byt2, byt2.length, InetAddress.getLocalHost(), 168);
//		 DatagramSocket ds2 = new DatagramSocket();
//		 ds2.send(dp2);
//		 ds2.close();
	}
}

你可能感兴趣的:(socket网络编程入门)