使用Java编写简单Socket客户端和服务端

简介

某同事要用Socket连接外围系统,帮忙写了个简单的Demo。
包含一个客户端和一个服务端的,仅是示例,比较简陋,服务端也没有用多线程。
直接贴代码了。

服务端

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

/**
 * Socket服务端示例
 */
public class SocketServer {
    ServerSocket serverSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;

    void runServer() {
        try {
            // 创建服务端监听
            serverSocket = new ServerSocket(31313, 10);

            // 等待客户端连接
            System.out.println("等待客户端连接...");
            connection = serverSocket.accept();
            System.out.println("收到客户端连接: " + connection.getInetAddress().getHostName());

            // 获取输入输出流
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());

            // 连接成功后,首先向客户端发成功消息
            sendMsg("连接成功");

            // 发送接收消息
            do {
                try {
                    message = (String) in.readObject();
                    System.out.println("client>" + message);

                    // 发送退出消息
                    if (message.equals("bye")) {
                        sendMsg("bye");
                    }
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                    System.err.println("数据格式无效");
                }
            } while (!message.equals("bye"));  //当对方消息为bye时退出循环
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // 关闭Socket连接
            try {
                in.close();
                out.close();
                serverSocket.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    void sendMsg(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        SocketServer server = new SocketServer();
        while (true) {
            server.runServer();
        }
    }
}

客户端

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

/**
 * Socket客户端示例
 */
public class SocketClient {
    Socket clientSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;

    void runClient() {
        try {
            // 连接到服务端
            clientSocket = new Socket("localhost", 31313);
            System.out.println("已连接到服务端");

            // 获取输入输出流
            out = new ObjectOutputStream(clientSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(clientSocket.getInputStream());

            // 发送接收消息
            do {
                try {
                    // 接收消息
                    message = (String) in.readObject();
                    System.out.println("server>" + message);

                    // 发送消息
                    sendMsg("hello");
                    sendMsg("hello again");

                    // 发送退出消息
                    message = "bye";
                    sendMsg(message);
                } catch (ClassNotFoundException ex) {
                    ex.printStackTrace();
                    System.err.println("数据格式无效");
                }
            } while (!message.equals("bye")); //当对方消息为bye时退出循环
        } catch (UnknownHostException ex) {
            ex.printStackTrace();
            System.err.println("无法连接到服务端");
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            // 关闭Socket连接
            try {
                in.close();
                out.close();
                clientSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    void sendMsg(String msg) {
        try {
            out.writeObject(msg);
            out.flush();
            System.out.println("client>" + msg);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        SocketClient client = new SocketClient();
        client.runClient();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,515评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,991评论 19 139
  • 年龄越大越明白,人生不可能事事顺心,处处完美,凡事没必要那么较真,人生难得糊涂。 越来越明白,内心的不快乐,是源于...
    盗梦笔记阅读 614评论 4 12
  • 有谁在意过一片雪花的空灵, 清淡晕染化作一幅水墨丹青。 谁能将千年的孤独暴露于天高日精, 感受下一刻彻骨的丝丝凉阴...
    change_mds阅读 256评论 10 9
  • 以前从来不总结,也没觉得有什么缺失,而且时间过去了,也不会再回来,做出来的总结也是挂念那些已经发生的不能改变的...
    凉快猫阅读 344评论 0 1