// =====================UDP网络编程===================================
/**UDP
* 客户端端
* 创建DatagramSocket,随机端口
* 创建DatagramPacket指定数据、长度、地址、端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
*/
Scanner sc = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
while (true) {
String line = sc.nextLine();
if("quit".equals(line)) {
break;
}
DatagramPacket packet =
new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet);
}
socket.close();
/**UDP
* 服务端
* 创建DatagramSocket,随机端口
* 创建DatagramPacket指定数据、长度、地址、端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
*/
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[1024],1024);
while (true) {
socket.receive(packet);
byte[] arr = packet.getData();
int len = packet.getLength();
String ipString = packet.getAddress().getHostAddress();
int port = packet.getPort();
System.out.println(ipString +":"+port+"//"+new String(arr,0,len));
}
// =====================TCP网络编程===================================
/**TCP
* 客户端
*/
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
Socket socket = new Socket("127.0.0.1", 6666);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(str);
System.out.println(br.readLine());
socket.close();
/**TCP
* 服务端
*/
ServerSocket server = new ServerSocket(6666);
System.out.println("服务器启动,监听6666端口");
while (true) {
Socket socket = server.accept();
new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
String str = br.readLine();
System.out.println("接收的是:"+str);
str = new StringBuilder(str).reverse().toString();
ps.println(str);
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
来源:CSDN
作者:qq_33332829
链接:https://blog.csdn.net/qq_33332829/article/details/104648521