TCP
三次握手四次挥手(三次干架,四次分手) 三次握手(三次干架) A:你瞅啥 B:瞅你咋地 A:干他 四次挥手(四次分手) A:我要走了 B:你真的要走了吗? B:你真的真的要走了吗? A:我真的要走了
package TCP;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(6000);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = null;
while ((str = br.readLine()) != null){
System.out.println("服务器接收数据为:" + str);
}
s.shutdownInput();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("我是小兰");
bw.flush();
br.close();
bw.close();
s.close();
}
}
package TCP;
import java.io.*;
import java.net.Socket;
public class TCPClient{
public static void main(String[] args) throws IOException {
Socket s = new Socket("127.0.0.1" ,6000);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bw.write("我是小明");
bw.flush();
s.shutdownOutput();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = null;
while ((str = br.readLine()) != null){
System.out.println("客户端接收数据为:" + str);
}
bw.close();
br.close();
s.close();
}
}
UDP
package UDP;
import java.io.IOException;
import java.net.*;
public class UdpClient {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9000);
byte[] buffer = new byte[1024];
DatagramPacket packetReceive = new DatagramPacket(buffer , 0 , buffer.length);
socket.receive(packetReceive);
System.out.println("服务端接收到的数据:" + new String(buffer , 0 , packetReceive.getLength()));
String str = "你好 生活";
InetAddress address = InetAddress.getByName("localhost");
int port = packetReceive.getPort();;
DatagramPacket packetSend = new DatagramPacket(str.getBytes() , 0 ,str.getBytes().length , address , port);
socket.send(packetSend);
socket.close();
}
}
package UDP;
import java.io.IOException;
import java.net.*;
public class UdpClient2 {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(9001);
String str = "你好 世界";
InetAddress address = InetAddress.getByName("localhost");
int port = 9000;
DatagramPacket packetSend = new DatagramPacket(str.getBytes() , 0 ,str.getBytes().length , address , port);
socket.send(packetSend);
byte[] buffer = new byte[1024];
DatagramPacket packetReceive = new DatagramPacket(buffer , 0 , buffer.length);
socket.receive(packetReceive);
System.out.println("客户端接收到的数据:" + new String(buffer , 0 , packetReceive.getLength()));
socket.close();
}
}
|