一、TCP
1、服务器端
package udpTest;import javax.management.MBeanRegistrationException;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class TCPService {public static void main(String[] args) {try {byte[] buf=new byte[512];ServerSocket serverSocket = new ServerSocket(1238);System.out.println("服务已启动:");Socket socket = serverSocket.accept();BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));//接收PrintStream printStream = new PrintStream(socket.getOutputStream());//发送while (true){String message=bufferedReader.readLine();//接收数据if(message!=null){if("exit".equals(message)){break;}System.out.println("接收客户端数据:"+message);//发送确认消息printStream.println("OK");printStream.flush();}}bufferedReader.close();printStream.close();socket.close();serverSocket.close();}catch (Exception ex){ex.printStackTrace();}}
}
2、客户端
package udpTest;import java.io.*;
import java.net.Socket;public class TCPClient {public static void main(String[] args) {try {Socket socket = new Socket("127.0.0.1", 1238);PrintStream printStream = new PrintStream(socket.getOutputStream());//发送BufferedReader bufferedReceiveReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));//接收while (true){//输入后发送消息System.out.println("请输入数据:");String message=new BufferedReader(new InputStreamReader(System.in)).readLine();printStream.println(message);printStream.flush();if(message.equals("exit")){break;}//接收服务器确认消息System.out.println("来自服务器的消息:"+bufferedReceiveReader.readLine());}printStream.close();socket.close();}catch (Exception e) {e.printStackTrace();}}
}
二、UDP
1、服务器端
package udpTest;import java.net.DatagramPacket;
import java.net.DatagramSocket;public class UDPService {public static void main(String[] args) {byte[] bytes = new byte[1024];DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);try {DatagramSocket datagramSocket = new DatagramSocket(1992);System.out.println("UDP服务已建立");datagramSocket.receive(datagramPacket);System.out.println("接收的数据");System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));}catch (Exception ex){ex.printStackTrace();}}
}
2、客户端
package udpTest;import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;public class UDPClient {public static void main(String[] args) {try {byte[] buf = "测试数据11".getBytes();DatagramPacket datagramPacket = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 1992);DatagramSocket datagramSocket = new DatagramSocket();datagramSocket.send(datagramPacket);}catch (Exception ex){ex.printStackTrace();}}
}