先补上一张神图
ok开始正文 现在我们就开始上java代码
UDP java编写
//udp服务器端
class UdpServer{
public static void main(String[] args) throws IOException {
//1.ip地址+端口号
System.out.println("udp服务器已经启动... 8080");
//创建服务器端端口号 默认使用本机Ip地址
DatagramSocket ds = new DatagramSocket(8080);
//服务器接受客户端1024个字节
byte[] bytes= new byte[1024];
//定义数据包
DatagramPacket dp = new DatagramPacket(bytes, bytes.length);
//接受客户端请求,将数据封装给数据包 如果客户端不往服务器端发送请求,就一直阻塞。
ds.receive(dp);
System.out.println("来源IP地址:"+dp.getAddress()+",端口号"+dp.getPort());
String result= new String(dp.getData(),0,dp.getLength());
System.out.println("服务器端接受客户端内容:"+result);
ds.close();
}
}
//先写服务器端 在写客户端
public class UdpClinet {
public static void main(String[] args) throws IOException {
System.out.println("udp客户端启动连接...");
//不传入端口号 作用客户端 创建一个socket客户端
DatagramSocket ds = new DatagramSocket();
String str="蚂蚁课堂";
byte[] strBytes= str.getBytes();
DatagramPacket dp = new DatagramPacket(strBytes, strBytes.length,InetAddress.getByName("127.0.0.1"),8080);
ds.send(dp);
ds.close();
}
}
TCP 由于网络请求的这些操作耗时操作,建议使用线程池,进行异步处理网络请求动作
class TcpServer {
public static void main(String[] args) throws IOException {
System.out.println("tcp协议服务器端启动..");
ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
// 创建服务器端连接
ServerSocket serverSocket = new ServerSocket(8080);
try {
// while (true) {
// 接受客户端请求 阻塞功能
Socket accept = serverSocket.accept();
newCachedThreadPool.execute(new Runnable(){
@Override
public void run() {
try {
InputStream inputStream = accept.getInputStream();
// 将字节流转换成String类型
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String result=new String(bytes,0,len);
System.out.println("服务器端接受客户端内容:"+result);
OutputStream outputStream = accept.getOutputStream();
outputStream.write("this is yes itmayiedu.com".getBytes());
} catch (Exception e) {
// TODO: handle exception
}
}
});
// }
} catch (Exception e) {
// TODO: handle exception
}finally {
serverSocket.close();
}
}
}
public class TcpClinet {
public static void main(String[] args) throws IOException {
System.out.println("socket tcp客户端启动....");
//创建socket客户端
Socket socket=new Socket("127.0.0.1",8080);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("我是蚂蚁课堂忠实粉丝....".getBytes());
socket.close();
}
}
蚂蚁课堂的余老师真的很赞
参考 蚂蚁课堂
参考 https://blog.csdn.net/u013777351/article/details/49226101