码迷,mamicode.com
首页 > 编程语言 > 详细

Java如何使套接字向单个客户端显示消息?

时间:2018-09-10 11:05:43      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:int   new   listening   --   serve   结果   single   client   static   

在Java编程中,如何使用套接字向单个客户端显示消息?

以下示例演示了如何使用Socket类的ssock.accept()方法向单个套接字客户端上显示消息。

package com.yiibai;

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketSingleClient {
    public static void main(String args[]) throws Exception {
        ServerSocket ssock = new ServerSocket(1234);
        System.out.println("Listening : ");
        Socket sock = ssock.accept();
        ssock.close();
        PrintStream ps = new PrintStream(sock.getOutputStream());

        for (int i = 10; i >= 0; i--) {
            ps.println(i + " from Java Source and Support.");
        }
        ps.close();
        sock.close();
    }
}
Java

上述代码示例将产生以下结果 -

Listening :
10 from Java Source and Support
9 from Java Source and Support
8 from Java Source and Support
7 from Java Source and Support
6 from Java Source and Support
5 from Java Source and Support
4 from Java Source and Support
3 from Java Source and Support
2 from Java Source and Support
1 from Java Source and Support
0 from Java Source and Support

Java如何使套接字向单个客户端显示消息?

标签:int   new   listening   --   serve   结果   single   client   static   

原文地址:https://www.cnblogs.com/borter/p/9617168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!