【问题标题】:Basic Java Sockets, Server can't send nor clients can recieve anything基本 Java 套接字,服务器无法发送,客户端也无法接收任何内容
【发布时间】:2011-06-10 01:44:52
【问题描述】:

我从“傻瓜的java-all-in-onedesk reference”一书中的教程中用Java编写了一个基本的客户端-服务器套接字程序,它包含3个类,BartServer,BartClient,BartQuote..基本上是什么BartServer.class 的作用是监听 BartClient.class,BartClient 在执行时会向 BartServer 发送命令,BartServer 会根据 BartClient 发送的内容进行回复..

如果“get”命令,BartServer 将回复从 BartQuote.class 生成的随机报价 否则“再见”将退出客户端... 我在本地主机上尝试过,客户端成功连接服务器,但是 BartServer 没有做任何事情,客户端也不会收到......命令无法响应或任何东西......我哪里出错了?对不起我的英语不好...

BartServer:

package socketBart;
import java.net.*;import java.io.*;import java.util.*;

public class BartServer {

public static void main(String[] args)
{
    int port = 1892;

    BartQuote bart = new BartQuote();

    try
    {
        System.out.println("BartServer 1.0");
        System.out.println("Listening on port "+port);
        ServerSocket ss = new ServerSocket(port);
        Socket s = ss.accept(); // WAITS for a client to connect, once connected, returns a socket object
        // once clients connects and socket s is created, it will proceed to the next line

        String client;
        client = s.getInetAddress().toString();
        System.out.println("Connected to "+ client);

        Scanner in = new Scanner(s.getInputStream()); //READS data sent to this server from CLIENTS
        PrintWriter out = new PrintWriter(s.getOutputStream()); //SENDS data FROM this server to CLIENTS

        out.println("Welcome to BartServer 1.0");// these lines are sent to the client
        out.println("Enter GET to get a quote or BYE to exit.");

        while (true)
        {
            String input = in.nextLine();
            if (input.equalsIgnoreCase("bye"))
                break;
            else if (input.equalsIgnoreCase("get"))
            {
                out.println(bart.getQuote());
                System.out.println("Serving "+ client);
            }
            else
                out.println("Huh?");
        }
        out.println("So long suckers!");
        s.close();

        System.out.println("Closed connection to " + client);
    }
    catch(Exception e){
        e.printStackTrace();
    }

}

}

巴特客户:

package socketBart;
import java.net.*;import java.util.*;import java.io.*;

public class BartClient {

public static void main(String[] args)
{
    int port = 1892;
    System.out.println("Welcome to the Bart Client\n");
    Socket s = getSocket(port);

    try
    {
        System.out.println("Connected on port " + port);

        Scanner in = new Scanner(s.getInputStream());
        PrintWriter out = new PrintWriter(s.getOutputStream(),true);

        //discard welcome message from server
        in.nextLine();

        //discard the exit instructions
        in.nextLine();

        //get a quote
        out.println("get");
        String quote = in.nextLine();

        //disconnect from server
        out.println("bye");
        s.close();

        //write the quote of the 'chalkboard'
        for (int i = 0; i < 20; i++)
            System.out.println(quote);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}

private static Socket getSocket(int port)
{
    Socket s;
    String host;
    InetAddress ip;

    Scanner sc = new Scanner(System.in);
    while (true)
    {
        System.out.print("Connect to server: ");
        host = sc.nextLine();

        try
        {
            ip = InetAddress.getByName(host);
            s = new Socket(ip,port);
            return s;
        }
        catch(UnknownHostException e)
        {
            System.out.println("The host is unknown.");
        }
        catch (IOException e)
        {
            System.out.println("Network error, check your port.");
        }//end catch
    }
}

}

巴特报价:

package socketBart;
import java.util.Random;
import java.util.ArrayList;

public class BartQuote {

ArrayList<String> q = new ArrayList<String>();

public BartQuote()
{
    q.add("I will not waste chalk");
    q.add("I will not skateboard in the halls");
    q.add("I will not burp in the class");
    q.add("I will not instigate a revolution");
    q.add("It's potato, not potatoe.");
    q.add("I will not encourage others to fly.");
    q.add("Tar is not a plaything.");
    q.add("I will not sell school property.");
    q.add("I will not get very far with this attitude");
    q.add("I will not sell land in Florida.");
    q.add("I will not grease the monkey bars.");
    q.add("I am not a dentist");
    q.add("I will finish what I started.");
    q.add("Hamsters cannot fly");
}

public String getQuote()
{
    int i = new Random().nextInt(q.size());
    return q.get(i);
}



}

【问题讨论】:

  • 你有没有试过在写入数据后刷新 PrintWriter?
  • 我倒是没有发现你的程序有什么问题,我有时也陷入了类似的情况......听起来很愚蠢,但尝试颠倒行的顺序:Scanner in = new Scanner(s.getInputStream ()); //读取从客户端发送到此服务器的数据 PrintWriter out = new PrintWriter(s.getOutputStream()); //从这个服务器向客户端发送数据............首先初始化然后在服务器上。
  • 我在客户端中编写了“get”和“bye”命令后确实刷新了...仍然无法正常工作
  • 我只是将代码复制到一起,刷新确实有助于更进一步。即我得到“服务/127.0.0.1”。所以我认为确保您的客户端和服务器在正确的时间刷新应该可以解决问题。确保你为客户做同样的事情,你应该没问题(也就是说,如果你的“协议”有效 - 我没有详细介绍逻辑,但似乎很容易假设)
  • 试过倒车,但无济于事...之前还是之后冲洗?我什至无法获得“欢迎使用 BartServer 1.0”

标签: java sockets


【解决方案1】:

在服务器上更改这一行:

PrintWriter out = new PrintWriter(s.getOutputStream());

到:

PrintWriter out = new PrintWriter(s.getOutputStream(), true);

这将改变,以便服务器在写入后始终刷新流。否则数据可能会在输出流的服务器缓冲区中徘徊。

请注意,您的客户端代码已设置为自动刷新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2016-07-19
    • 2012-12-14
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多