简体   繁体   English

简单的客户端/服务器程序Java

[英]Simple client/server program java

I am trying aa very simple server/client program but can't seem to get it working - "acc" and "waiting for connection" is printed however "connection" is never printed am I doing something wrong ? 我正在尝试一个非常简单的服务器/客户端程序,但似乎无法使其正常工作-打印了“ acc”和“等待连接”,但是从未打印“连接”,这是我做错了吗?

Client code: 客户代码:

    Socket s;
    String serverIP = "127.0.0.1";
    int serverPortNo = 9010;

    public Frame(){

    try{
        s = new Socket(serverIP, serverPortNo);
    }
    catch(IOException e){
        System.out.println("error : "+ e.getMessage());
    }
}

Server code : 服务器代码:

public class Server {

ServerSocket ss;

public Server(int port){

    try{
        ss = new ServerSocket(port);
        acceptConnections();
    }
    catch(IOException e){
        System.out.println(e.getMessage());
    }
}

public void acceptConnections(){
    Socket s;
    System.out.println("acc");

    while(true){
        try{
            System.out.println("waiting for connections");
            s= ss.accept();
            System.out.println("connection");

        }
        catch(Exception e){
            System.out.println("error : " + e.getMessage());
        }
    }
}

Main method: 主要方法:

public class Main {

public static void main(String[] args){
    new Server(9010);
    new Frame();
}
}

You need to start server in a separate thread. 您需要在单独的线程中启动服务器。 For now your main application starts server and waits for clients but client is never started. 现在,您的主应用程序启动服务器并等待客户端,但客户端从未启动。 Please try to change your main method to look like this 请尝试将您的main方法更改为如下形式

try {
  Thread t = new Thread(new Runnable() {
         public void run() {
             new Server(9010);
         }
     });
  t.start();
  new Frame();
  t.join();
} catch(Exception e) { e.printStackTrace(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM