TCP协议:Socket,可靠的服务:A-->B 三次握手
UDP协议:不可靠,短信功能
TCP:
- package protocol;
- import java.net.*;
- import java.io.*;
- public class TCPServer {
- public static void main(String[] args) throws Exception{
- //使用ServerSocket
- ServerSocket server=null;
- //每一个用户在程序中就是一个Socket
- Socket client=null;
- server=new ServerSocket(8888);
- //等待客户端连接
- client=server.accept();
- PrintWriter out=null;
-
- //准备向客户端打印信息
- out=new PrintWriter(client.getOutputStream());
- out.println("Hello");
- out.close(); //关闭流
- client.close();
- server.close();
- }
- }
- package protocol;
- import java.io.*;
- import java.net.*;
- public class TCPClient {
- public static void main(String[] args)throws Exception {
- //表示一个客户端的Socket
- Socket client=null;
- //表示一个客户端的输入信息
- BufferedReader buf=null;
- client=new Socket("localhost",8888);
- buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
- System.out.println(buf.readLine());
- buf.close();
- client.close();
- }
- }
UDP:
- package protocol;
- import java.net.*;
- import java.io.*;
- public class UDPServer {
- public static void main(String[] args)throws Exception {
-
- DatagramSocket ds=null;
- DatagramPacket dp=null;
- //要保证UDP有一个运行的端口
- ds=new DatagramSocket(5000);
- String s="Hello MLDN haha";
- //建立服务器端的一个发送端
- dp=new DatagramPacket(s.getBytes(),0,s.length(),InetAddress.getByName("localhost"),9999);
- ds.send(dp);
- ds.close();
- }
- }
- package protocol;
- import java.io.*;
- import java.net.*;
- public class UDPServerInput {
- public static void main(String[] args) throws Exception{
- DatagramSocket ds=null;
- DatagramPacket dp=null;
- //要保证UDP有一个运行的端口
- ds=new DatagramSocket(6000);
- //String s="Hello MLDN haha";
- //BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
- System.out.println("请输入要发送的信息:");
- //s=buf.readLine();
- byte b[]=new byte[1024];
- int len=System.in.read(b);
- //System.out.println(s.length());
- //dp=new DatagramPacket(s.getBytes(),0,s.length(),InetAddress.getByName("localhost"),9999);
- //dp.setData(s.getBytes());
- dp=new DatagramPacket(b,0,len,InetAddress.getByName("localhost"),9999);
- ds.send(dp) ;
- ds.close();
- }
- }
- package protocol;
- import java.io.*;
- import java.net.*;
- public class UDPClient {
- public static void main(String[] args) throws Exception{
- DatagramSocket ds=null;
- DatagramPacket dp=null;
- //手机发信息和接收信息是有大小限制的
- byte b[]=new byte[1024];
- //在9999端口上一直等待信息到来
- ds=new DatagramSocket(9999);
- dp=new DatagramPacket(b,b.length);
- ds.receive(dp);
- //从数据包中取出数据
- String str=new String(dp.getData(),0,dp.getLength());
- System.out.println("接收到的数据为:"+str);
- ds.close();
- }
- }
阅读(2336) | 评论(1) | 转发(0) |