注册 登录
编程论坛 JAVA论坛

运行后就是显示不出来是第几个客户端

brokenheart 发布于 2016-06-19 00:24, 1918 次点击
实现一个网络应用:
  客户端会给服务器发送一个字符串服务器会把这个字符串转换成大写形式发回给客户端并由客户端显示,同时,服务器会告知客户端,他是第几个客户端。
程序代码:
import *;
import *;

public class Server {
    static int i=1;
    public Server() {
        try {
            ServerSocket ss = new ServerSocket(11038);
            Socket s = ss.accept();
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("hihi");
            System.out.println("原字母为:"+dis.readUTF());
            dos.flush();
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
        }
    }
    public static void main(String[] args) {
        
         new Server();
         while(true){
            System.out.println("你是第"+i+"个客户端");
            i++;
        }
    }
}

程序代码:
import *;
import *;

public class client {
    public client() {
        try {
            Socket s = new Socket("localhost", 11038);
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
            DataInputStream dis = new DataInputStream(s.getInputStream());
            dos.writeUTF("hello");
            String info = dis.readUTF().toUpperCase();
            System.out.println("转化为大写字母后为:"+info);
            dos.flush();
            dos.close();
            dis.close();
            s.close();
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
        }
    }
    public static void main(String args[]) {
        new client();
    }
}

运行后,程序就跑不停,各位大神帮我看看该如何
1 回复
#2
jinjoxie2016-06-21 09:25
import *;
import *;

public class Server {
    static int i=1;
    public Server() {
        try {
            ServerSocket ss = new ServerSocket(11038);

            while(true){
                Socket s = ss.accept();
                DataOutputStream dos = new DataOutputStream(s.getOutputStream());
                DataInputStream dis = new DataInputStream(s.getInputStream());
                dos.writeUTF("hihi");
                System.out.println("原字母为:"+dis.readUTF());
                dos.flush();
                System.out.println("你是第"+i+"个客户端");
                i++;
            }
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
        }
    }
    public static void main(String[] args) {        
         new Server();
    }  
}

ServerSocket每次调用accept后就一直等待下个客户端接入,调用一次只接入一个的,你想监听多个客户端就要多次掉用accept
1