Java 网络编程 TCP UDP 简单案例
UDP
upd是面向无连接,基于数据包发送,安全系数低的通讯协议
/**
* udp发送端
*/
@AfterTestClass
public void test01() throws Exception{
String s = "nxnnxnx";
//数据包
DatagramPacket packet = new DatagramPacket(s.getBytes(), s.getBytes().length, InetAddress.getLocalHost(), 8899);
//数据包socket对象
DatagramSocket socket = new DatagramSocket();
//发送
socket.send(packet);
//关闭资源
socket.close();
}
/**
* 接收端
*/
@BeforeTestMethod
public void test03()throws Exception{
//数据包socket对象
DatagramSocket socket = new DatagramSocket();
//字节容器
byte[] bytes = new byte[2048];
//数据包对象
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
//接收
socket.receive(datagramPacket);
int len = datagramPacket.getLength();
//打印内容
System.out.println("接收者"+new String(bytes,0,len));
String ip = datagramPacket.getAddress().getHostAddress();
int port = datagramPacket.getPort();
socket.close();
}
TCP
tcp是面向连接,三次握手四次挥手的,基于IO传输的可靠协议,不受内容大小约束
TCP 服务端
package com.example.demo;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*@author Kaki Nakajima
*@desc TCP 服务端
*/
public class TcpServer {
public static void main(String[] args)throws Exception {
System.out.println("init...........");
ServerSocket server = new ServerSocket();
while (true){
Socket accept = server.accept();
new Thread(()->{
try (
BufferedInputStream bin = new BufferedInputStream(accept.getInputStream());
FileOutputStream fout = new FileOutputStream(System.currentTimeMillis() + ".jpg");
) {
byte[] b = new byte[1024 * 8];
int len = -1;
while ((len=bin.read(b)!=-1)){
fout.write(b, 0, len);
}
fout.close();
bin.close();
accept.getOutputStream().write("sccess!".getBytes());
accept.close();
}catch (Exception e){
e.printStackTrace();
}
})
}
}
}
TCP客户端
package com.example.demo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.net.Socket;
/**
*@author Kaki Nakajima
*@desc TCP 客户端
*/
public class TcpClent {
public static void main(String[] args) throws Exception{
BufferedInputStream bis = new BufferedInputStream(new
FileInputStream("test.jpg"));
Socket socket = new Socket("localhost", 6666);
BufferedOutputStream bos = new
BufferedOutputStream(socket.getOutputStream());
byte[] b = new byte[1024 * 8 ];
int len ;
while (( len = bis.read(b))!=-1) {
bos.write(b, 0, len);
}
//通知接收方,输出完毕
socket.shutdownOutput();
System.out.println("⽂件发送完毕");
InputStream in = socket.getInputStream();
byte[] back = new byte[20];
in.read(back);
System.out.println(new String(back));
in.close();
socket.close();
bis.close();
}
}
欢迎点赞关注收藏哦 ,码云搜索KakiNakajima