UDP
Send.java
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Send {
/*
按照下面的要求实现程序
UDP发送数据:数据来自于键盘录入,直到输入的数据是886,发送数据结束
UDP接收数据:因为接收端不知道发送端什么时候停止发送,故采用死循环接收
*/
public static void main(String[] args) throws IOException {
// 创建对象DatagramSocket对象(快递公司)
DatagramSocket ds = new DatagramSocket();
// 打包数据
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入您要发送的信息:");
String s = sc.nextLine();
if ("886".equals(s)){
break;
}
byte[] b = s.getBytes();
InetAddress byName = InetAddress.getByName("127.0.0.1");
int port = 10086;
DatagramPacket dp = new DatagramPacket(b,b.length,byName,port);
ds.send(dp);
}
ds.close();
}
}
Receive.java
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class Receive {
public static void main(String[] args) throws IOException {
DatagramSocket ds = new DatagramSocket(10086);
// 接受数据包
byte[] bytes = new byte[1024];
DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
while (true) {
ds.receive(dp);
// 解析数据包
byte[] data = dp.getData();
int length = dp.getLength();
String ip = dp.getAddress().getHostAddress();
String name = dp.getAddress().getHostName();
// 打印数据
System.out.println("ip为:"+ip+",主机名为:"+name+"的人,发送了数据:"+new String(data,0,length));
}
}
}
TCP
Client.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
// TCP协议,发送数据
// 1.创建Socket对象,细节在创建对象的同时会连接服务端
// 如果连接不上,代码会报错
Socket socket = new Socket("127.0.0.1",8080);
// 2.可以从连接通道中获取输出流
OutputStream os = socket.getOutputStream();
os.write("Hello world ".getBytes());
os.close();
socket.close();
}
}
Serive.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Service {
public static void main(String[] args) throws IOException {
// TCP协议,接收数据
// 1.创建对象ServerSocket
ServerSocket ss = new ServerSocket(8080);
// 2.监听客户端的链接
Socket socket = ss.accept();
// 3.从链接通道中获取输入流读取数据
/* InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);*/
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int b;
while ((b = br.read()) != -1){
System.out.print((char)b);
}
}
}