- public class TCP_lient {
- public static void main(String[] args) {
- String str = null;
- Socket clientSocket; // 创建客户端套接字
- DataInputStream in = null; // 创建DataInputStream对象
- DataOutputStream out = null; // 创建DataOutputStream对象
- try {
- clientSocket = new Socket("127.0.0.1", 4331); // 实例化Socket对象
- //clientSocket = new Socket("192.168.152.139", 6379);
- in = new DataInputStream(clientSocket.getInputStream()); // 实例化DataInputStream对象
- // 实例化DataOutputStream对象
- out = new DataOutputStream(clientSocket.getOutputStream());
- out.writeUTF("你好!!"); // 写数据
- while (true) {
- str = in.readUTF(); // 读取流中数据
- out.writeUTF(((int) (Math.random() * 10) + 1) + ""); // 向流中写入0到10之间的随机数
- System.out.println("客户端收到:" + str); // 输出信息
- Thread.sleep(1000); // 线程休眠
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public class TCP_Server {
- public static void main(String[] args) {
- ServerSocket serverSocket = null; // 创建服务器端套接字
- Socket clientSocket = null; // 创建客户端套接字
- String str = null;
- DataOutputStream out = null; // 创建DataOutputStream类对象
- DataInputStream in = null; // 创建DataInputStream类对象
- try {
- serverSocket = new ServerSocket(4331); // 实例化ServerSocket对象
- clientSocket = serverSocket.accept(); // 接收客户的套接字连接呼叫
- in = new DataInputStream(clientSocket.getInputStream()); // 实例化DataInputStream对象
- out = new DataOutputStream(clientSocket.getOutputStream()); // 实例化DataOutputStream对象
- while (true) {
- str = in.readUTF(); // 读取客户放入连接中的信息
- out.writeUTF("hello,我是服务器"); // 通过输出流向线路中写信息
- out.writeUTF(str);
- System.out.println("服务器收到:" + str);
- Thread.sleep(1000); // 线程休眠
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
复制代码 |