/**
* Socket编程
* https://www.jianshu.com/p/b04930d2b85e
* https://www.jianshu.com/p/a89e9487a06c
* https://www.jianshu.com/p/f4b30dd0e39d
* Socket,专业术语套接字。它把TCP/IP封装成了调用接口,开发者
* 可以通过调用Socket相关API来实现网络通讯,在Java中也存在Socket
* 相关的API,主要分为基于UDP传输协议的Socket和基于TCP传输协议的
* Socket。
* <p>
* UDP Socket
* 发送方:
* 1.首先创建udp的socket服务。
* 2.将需要发送的数据放在数据包DatagramSocket中,
* DatagramSocket会根据UDP协议对数据包、IP、端口号进行封装。
* 3.通过udp的socket服务将数据包发送。
* 4.最后将udp服务关闭。
* 接收方:
* 1.创建udp的socket服务,并且明确自己的端口号
* 2.创建DatagramSocket用来解析数据接收到的数据包
* 3.将数据接收到数据包DatagramSocket中
* 4.通过DatagramSocket解析数据
* 5.关闭服务
* <p>
* 因为UDP是无连接的不可靠传输,所以接收方需要在发送方发送数据之前就启动,
* 否则会接收不到数据,也就是说必须先运行UDPSocketReceive再运行UDPSocketSend。
* <p>
* TCP Socket
* TCP基于client-server是面向连接的可靠传输,
* TCP Socket分为Socket和ServerSocket对应着client和server
*/
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//UDP Socket 发送
try {
DatagramSocket ds = new DatagramSocket();
String str = "hello";
byte[] bytes = str.getBytes();
InetAddress inetAddress = InetAddress.getByName("111.205.51.135");
DatagramPacket datagramPacket = new DatagramPacket(
bytes,
0,
bytes.length,
inetAddress,
6666);
ds.send(datagramPacket);
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
//UDP Socket 接收
try {
DatagramSocket ds = new DatagramSocket(6666);
byte[] bytes = new byte[1024];
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
ds.receive(datagramPacket);
InetAddress address = datagramPacket.getAddress();
int port = datagramPacket.getPort();
String content = new String(datagramPacket.getData(),
0, datagramPacket.getLength());
ds.close();
} catch (Exception e) {
e.printStackTrace();
}
//TCP Socket 发送
Socket socket = new Socket();
InetSocketAddress inetSocketAddress =
new InetSocketAddress("111.205.51.135", 6666);
try {
socket.connect(inetSocketAddress);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello".getBytes());
outputStream.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
//TCP Socket接收
try {
ServerSocket serverSocket = new ServerSocket(6666);
Socket socket1 = serverSocket.accept();
InputStream inputStream = socket1.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.d("dww", line);
}
serverSocket.close();
socket1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
网友评论