标签:user 需要 面向 int stream tcp 一个 文件 eth
通信协议:传输码率,代码结构,传输控制…..
TCP
面向连接,稳定
三次握手,四次挥手
UDP
面向无连接,不稳定
客户端、服务端:没有明确的界限
客户端
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port = 9999;
Socket socket = new Socket(serverIP,port);创建一个socket连接
OutputStream os = socket.getOutputStream();发送消息 IO流
服务器
建立服务的端口 ServerSocket
等待用户的链接 accept
接收用的消息
eg:文件上传
客户端
public class Demo1 {
public static void main(String[] args) throws IOException {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("C:\\Users\\张孛\\Desktop\\1许巍 - 曾经的你.mp3"));
Socket socket = new Socket("127.0.0.1",5555);
OutputStream outputStream = socket.getOutputStream();
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
outputStream.write(bytes,0,len);
}
socket.shutdownOutput();
System.out.println("11111111111111");
InputStream inputStream1 = socket.getInputStream();
byte[] bytes1 = new byte[1024];
inputStream1.read(bytes1);
System.out.println(new String(bytes1));
socket.close();
}
}
服务器
public class Demo2 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5555);
while (true){
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(System.currentTimeMillis()+""+new Random().nextInt(100)+".mp3"));
byte[] bytes = new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
bufferedOutputStream.write(bytes,0,len);
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("已收到信息".getBytes());
socket.close();
}
}
}
UDP
不需要连接服务器
public class UdpClientDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket();
String msg = "发送给服务器";
InetAddress localhost = InetAddress.getByName("localhost");
int port = 5555;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
socket.send(packet);
socket.close();
}
}
接收端
public class UdpServerDemo01 {
public static void main(String[] args) throws Exception {
DatagramSocket socket = new DatagramSocket(5555);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength()));
socket.close();
}
}
标签:user 需要 面向 int stream tcp 一个 文件 eth
原文地址:https://www.cnblogs.com/arroa/p/11992905.html