Java Socket简单例子、readLine()、readUTF()

转载请标明出处:http://blog.csdn.net/xx326664162/article/details/51752701 文章出自:薛瑄的博客

你也可以查看我的其他同类文章,也会让你有一定的收货!

Socket简单例子

服务端:

public class Server {

    public static final int PORT = 12345;//监听的端口号

    public static void main(String[] args) {
//        System.out.println("服务器启动...\n");
        System.out.println("server start...\n");
        Server server = new Server();
        server.init();
    }

    public void init() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            while (true) {
                // 一旦有堵塞, 则表示服务器与客户端获得了连接
                Socket client = serverSocket.accept();
                // 处理这次连接
                new HandlerThread(client);
            }
        } catch (Exception e) {
            System.out.println("服务器异常: " + e.getMessage());
        }
    }

    private class HandlerThread implements Runnable {
        private Socket socket;

        public HandlerThread(Socket client) {
            socket = client;
            new Thread(this).start();
        }

        public void run() {
            try {
                // 读取客户端数据
                DataInputStream input = new DataInputStream(socket.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
                // 向客户端回复信息
                DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                while (true) {
//                    String clientInputStr = input.readUTF();//这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
                    String clientInputLine = bufferedReader.readLine();
                    // 处理客户端数据
//                System.out.println("客户端发过来的内容:" + clientInputStr);
//                    System.out.println("response from client:" + clientInputStr);
                    System.out.println("response from client:" + clientInputLine);

//                System.out.print("请输入:\t");
//                    System.out.print("input:\t");
//                    // 发送键盘输入的一行
//                    String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
//                    out.writeUTF(s);

                }
//                out.close();
//                input.close();
            } catch (Exception e) {
                System.out.println("服务器 run 异常: " + e.getMessage());
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (Exception e) {
                        socket = null;
                        System.out.println("服务端 finally 异常:" + e.getMessage());
                    }
                }
            }
        }
    }

}

客户端:

public class Client {
    public static final String IP_ADDR = "localhost";//服务器地址
    public static final int PORT = 12345;//服务器端口号

    public static void main(String[] args) {
        System.out.println("start client...");
//      System.out.println("当接收到服务器端字符为 \"OK\" 的时候, 客户端将终止\n");
        System.out.println("stop client when received char is \"OK\" \n");
        Socket socket = null;
        try {
            //创建一个流套接字并将其连接到指定主机上的指定端口号
            socket = new Socket(IP_ADDR, PORT);
            //读取服务器端数据
            DataInputStream input = new DataInputStream(socket.getInputStream());
            //向服务器端发送数据
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            while (true) {

                out.write("12123\n".getBytes());
//              System.out.print("请输入: \t");
                System.out.print("input: \t");
                String str = new BufferedReader(new InputStreamReader(System.in)).readLine();
//                out.writeUTF(str);
                out.write(str.getBytes());
                String ret = input.readUTF();
//                System.out.println("服务器端返回过来的是: " + ret);
                System.out.println("response from server : " + ret);
                // 如接收到 "OK" 则断开连接
                if ("OK".equals(ret)) {
//                    System.out.println("客户端将关闭连接");
                    System.out.println("client will close");
                    Thread.sleep(500);
                    break;
                }
            }
            out.close();
            input.close();
        } catch (Exception e) {
            System.out.println("客户端异常:" + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    socket = null;
                    System.out.println("客户端 finally 异常:" + e.getMessage());
                }
            }
        }
    }
}

read()

如果服务器已经断开socket连接,此时再客户端使用boolean b1 = mSocket.isConnected();还是会返回true,但是使用read()会一直返回-1

之所以会出现连接断开了,但是isConnected()还是会返回true,我认为是这样的,因为tcp连接只是一种状态,服务端和客户端保持这个状态,表示有数据到来,各自会接收,也可以向对方发送数据。其实世界上所有的可以上网的设备都已经存在了物理连接,只不过需要通过各自设备状态(比如:tcp的各个状态),来允许来和谁通信。

readLine()

BufferedReader的readLine方法是一次读一行的,这个方法是阻塞的,

直到它读到了一行数据为止程序才会继续往下执行

直到程序遇到了换行符或者是对应流的结束符readLine方法才会认为读到了一行,

才会结束其阻塞,让程序继续往下执行

所以在写入的时候字符串结尾用换行符就行了 bw.write(“你好服务器\n”);

readUTF()

readUTF读取的必须是writeUTF写下的字符串。

参考:

在Java中readUTF()怎莫用?
android socket readline()方法读不到值的问题
一个 Java 的 Socket 服务器和客户端通信的例子

关注我的公众号,轻松了解和学习更多技术
这里写图片描述

  • 9
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
import java.io.*; import java.net.*; import java.util.*; import java.lang.*; public class Server extends ServerSocket { private static ArrayList User_List = new ArrayList(); private static ArrayList Threader = new ArrayList(); private static LinkedList Message_Array = new LinkedList(); private static int Thread_Counter = 0; private static boolean isClear = true; protected static final int SERVER_PORT = 10000; protected FileOutputStream LOG_FILE = new FileOutputStream( "d:/connect.log", true); public Server() throws FileNotFoundException, IOException { super(SERVER_PORT); // append connection log // Calendar now = Calendar.getInstance(); // String str = "[" + now.getTime().toString() + // "] Accepted a connection"; // byte[] tmp = str.getBytes(); // LOG_FILE.write(tmp); try { Socket socket = accept(); while (true) { new ServerReaderThread(socket); new ServerWriterThread(socket); } } finally { close(); } } public static void main(String[] args) throws IOException { new Server(); } // --- CreateServerThread class ServerReaderThread extends Thread { private Socket client; private BufferedReader in; private PrintWriter out; private String Username; public ServerReaderThread(Socket s) throws IOException { client = s; in = new BufferedReader(new InputStreamReader(client .getInputStream())); out = new PrintWriter(client.getOutputStream(), true); start(); } public void run() { try { int flag = 0; Thread_Counter++; String line = in.readLine(); while (!line.equals("bye")) { out.println(line); line = in.readLine(); } out.println("--- See you, bye! ---"); // System.out.println("--- See you, bye! ---"); client.close(); } catch (IOException e) { } finally { try { client.close(); } catch (IOException e) { } Thread_Counter--; } } } // --- CreateServerThread class ServerWriterThread extends Thread { priva

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛瑄

文章不错,请博主吃包辣条

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值