浅谈java的TCP和UDP编程(附实例讲解)

网友投稿 213 2023-05-11


浅谈java的TCP和UDP编程(附实例讲解)

TCP

客户端:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class MyClient {

public static void main(String[] args) throws Exception{

Socket socket = null;

BufferedReader in = null;

PrintWriter out = null;

BufferedReader input = null;

// 请求指定ip和端口号的服务器

socket = new Socket("127.0.0.1",3333);

while(true){

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

out = new PrintWriter(socket.getOutputStream(), true);

// 接收控制台的输入

input = new BufferedReader(new InputStreamReader(System.in));

// out.println("this is client info!");

String info = input.readLine();

out.println(info);

String str = in.readLine();

System.out.println("客户端显示--》服务器的信息:" + str);

}

//in.close();

//out.close();

}

}

服务端:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class MyServices {

public static void main(String[] args) throws Exception{

ServerSocket ss =SWTweu null;

Socket socket = null;

BufferedReader in = null;

PrintWriter out = null;

BufferedReader input = null;

// 监听3333端口

ss = new ServerSocket(3333);

// 等待接收客户端的请求

socket = ss.accept();

while(true){

// 获取连接对象的输入流

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

// 获取客户端的输入信息

String str = in.readLine();

input = new BufferedReader(new InputStreamReader(System.in));

System.out.println("服务器显示-->客户端输入数据:" + str);

out = new PrintWriter(socket.getOutputStream(),true);

// 将数据输出到客户端

// out.println("hehe");

String info = input.readLine();

out.println(info);

}

// in.close();

// out.flush();

// out.close();

}

}

UDP

客户端:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

public class UDPClient {

public static void main(String[] args) throws Exception {

DatagramSocket ds = null;

DatagramPacket dp = null;

byte[] buf = new byte[1024];

ds = new DatagramSocket(3333);

dp = new DatagramPacket(buf, 1024);

// 接收数据,放入数据报

ds.receive(dp);

// 从数据报中取出数据

String info = new String(dp.getData(),0, dp.getLength());

System.out.println("接收到的信http://息是:" + info);

}

}

服务端:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPServer {

public static void main(String[] args) throws Exception {

DatagramSocket ds = null;

DatagramPacket dp = null;

// 构建发送对象

ds = new DatagramSocket();

// 将数据打包-->打成数据报

String info = "hello world!";

dp = new DatagramPacket(info.getBytes(), info.length(), InetAddress.getByName("localhost"),3333);

// 发出数据报

ds.send(dp);

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:关于break和continue以及label的区别和作用(详解)
下一篇:java接口实现接口(java 接口实现接口)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~