欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA 服务端和客户端Socket通信的简单例子

程序员文章站 2022-04-24 13:26:17
...

服务端:

package socketTest;

import java.net.*;
import java.io.*;

public class GreetingSocket {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(6066);
            while (true) {
                //wait Client connect
                Socket client = serverSocket.accept();
                //get Client message
                DataInputStream input = new DataInputStream(client.getInputStream());
                String clientInputStr = input.readUTF();
                System.out.println(clientInputStr);
                //send Client message
                DataOutputStream output = new DataOutputStream(client.getOutputStream());
                String clientOutputStr = "Server";
                output.writeUTF(clientOutputStr);
                //close input output
                input.close();
                output.close();
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
} 

客户端:

package socketTest;

import java.io.*;
import java.net.*;

public class ClientSocket {
    public static void main(String[] args) {
        Socket socket = null;
        while (true) {
            try {
                //connect Server
                socket = new Socket("localhost", 6066);
                //send Server message
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
                out.writeUTF(str);
                //get Server message
                DataInputStream input = new DataInputStream(socket.getInputStream());
                String serverInputStr = input.readUTF();
                System.out.println(serverInputStr);
                //close output input
                out.close();
                input.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}


相关标签: JAVA