Java Sockets:我的服务器输入流不会从客户端输出流读取?

发布于 2024-12-31 22:01:37 字数 5183 浏览 0 评论 0原文

编辑:我知道它很长,但是有人知道如何对套接字进行编程吗?

我的问题让我有点困惑。我有一台服务器在一台计算机上运行,​​在另一台计算机上有一个客户端连接到它。当我从客户端将消息输入控制台并发送它时,服务器似乎没有收到它。任何人都知道为什么,因为过去 3 个小时我一直在测试打印到控制台,但无法弄清楚这一点。我对套接字比较陌生,所以如果我只是个白痴,请不要太严厉。

这是我的客户端代码:

import java.net.*;
import java.util.Scanner;
import java.io.*;

public class SocketClient {

public static void main(String [] args) {
    String host = "************";
    int port = 25565;

    StringBuffer instr = new StringBuffer();
    String TimeStamp;
    System.out.println("SocketClient initialized");

    try {
        InetAddress address = InetAddress.getByName(host);
        Socket connection = new Socket(address, port);

        BufferedOutputStream bos = new     BufferedOutputStream(connection.getOutputStream());
        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        Scanner scan = new Scanner(System.in);
        String message = scan.nextLine();

        TimeStamp = new java.util.Date().toString();
        String process = "Server called on " + host + ":" + port + " at " + TimeStamp + ": " + message + (char) 13;

        osw.write(process);
        osw.flush();

        BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());

        InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

        int c;
        while ( (c = isr.read()) != 13)
            instr.append( (char) c);

        connection.close();
        System.out.println(instr);

    } catch (UnknownHostException e) {
        System.err.println("UnknownHostException: " + e);
    } catch (IOException e) {
        System.err.println("IOExcepion: " + e);
    }
}
}

这是将客户端连接到服务器的代码:

import java.io.IOException;
import java.net.*;

public class MultipleSocketServer {

public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = {"", ""};
public static ServerSocket socket;

public static void main(String[] args) {
    System.out.println("Server starting...");
    try {
        ServerSocket socket = new ServerSocket(port);
        while(true) {
            Socket connection = socket.accept();
            String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
            loop:
            for(int i = 0; i < connected.length; i++) {
                if(connected[0].equals(ip) || connected[1].equals(ip)) {
                    break loop;
                }else if(!connected[i].equals(ip)) {
                    connected[i] = ip;
                    System.out.println(ip);
                    MultiServer_Client client = new     MultiServer_Client(connection, i);
                    Thread run = new Thread(client);
                    run.start();
                    break loop;
                }
            }
        }
    } catch (IOException e1) {
        System.out.println("Could not bind server on: " + port);
        System.exit(-1);
    }
}
}

这是我处理连接的每个客户端的代码:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class MultiServer_Client implements Runnable {

public String time;
public Socket client;
public StringBuffer process = new StringBuffer();

public BufferedInputStream inputStream;
public InputStreamReader reader;

public BufferedOutputStream outputStream;
public OutputStreamWriter writer;

public boolean connected = true;

public int ID;

public MultiServer_Client(Socket connection, int i) {
    client = connection;
    ID = i;
    try {
        inputStream = new BufferedInputStream(client.getInputStream());
        reader = new InputStreamReader(inputStream);

        outputStream = new BufferedOutputStream(client.getOutputStream());
        writer = new OutputStreamWriter(outputStream, "US-ASCII");
    } catch (IOException e) {
        System.out.println("IOException: " + e);
    }
    System.out.println("Client connected...");
    write("Connected to " + MultipleSocketServer.name);
}

public void run() {
    while(connected) {
        write("hi");
    }
    System.out.println("Disconnecting client...");
}

public void write(String authen) {
    try {
        time = new java.util.Date().toString();
        String message = time + ": " + authen + (char) 13;
        writer.write(message);
        writer.flush();
    } catch (IOException e) {
        connected = false;
        MultipleSocketServer.connected[ID] = "";
    }
}

public void read() {
    //read from client
    int character;
    process = new StringBuffer();
    try {
        while ((character = reader.read()) != 13) {
            process.append((char) character);
        }
        System.out.println(process);
        process.delete(0, process.length());
    } catch (IOException e) {
        connected = false;
        MultipleSocketServer.connected[ID] = "";
    }
}
}

抱歉,如果我帮不了什么忙。正如我所说,我是套接字新手,其他人似乎对此没有任何问题...谢谢:)

EDIT: Ik it is long but does anyone know how to program sockets??

My problem is confusing me a bit. I have a server running on one computer and on another, I have a client connected to it. When I type a message from the client into the console and send it, the server does not seem to receive it. Anybody know why because I have been testing with printing to the console for the last 3 hours and cannot figure this out. I am relatively new to sockets so don't be too harsh if I am just being an idiot.

Heres my code for the client side:

import java.net.*;
import java.util.Scanner;
import java.io.*;

public class SocketClient {

public static void main(String [] args) {
    String host = "************";
    int port = 25565;

    StringBuffer instr = new StringBuffer();
    String TimeStamp;
    System.out.println("SocketClient initialized");

    try {
        InetAddress address = InetAddress.getByName(host);
        Socket connection = new Socket(address, port);

        BufferedOutputStream bos = new     BufferedOutputStream(connection.getOutputStream());
        OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

        Scanner scan = new Scanner(System.in);
        String message = scan.nextLine();

        TimeStamp = new java.util.Date().toString();
        String process = "Server called on " + host + ":" + port + " at " + TimeStamp + ": " + message + (char) 13;

        osw.write(process);
        osw.flush();

        BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());

        InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

        int c;
        while ( (c = isr.read()) != 13)
            instr.append( (char) c);

        connection.close();
        System.out.println(instr);

    } catch (UnknownHostException e) {
        System.err.println("UnknownHostException: " + e);
    } catch (IOException e) {
        System.err.println("IOExcepion: " + e);
    }
}
}

Here is the code to connect the client to the server:

import java.io.IOException;
import java.net.*;

public class MultipleSocketServer {

public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = {"", ""};
public static ServerSocket socket;

public static void main(String[] args) {
    System.out.println("Server starting...");
    try {
        ServerSocket socket = new ServerSocket(port);
        while(true) {
            Socket connection = socket.accept();
            String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
            loop:
            for(int i = 0; i < connected.length; i++) {
                if(connected[0].equals(ip) || connected[1].equals(ip)) {
                    break loop;
                }else if(!connected[i].equals(ip)) {
                    connected[i] = ip;
                    System.out.println(ip);
                    MultiServer_Client client = new     MultiServer_Client(connection, i);
                    Thread run = new Thread(client);
                    run.start();
                    break loop;
                }
            }
        }
    } catch (IOException e1) {
        System.out.println("Could not bind server on: " + port);
        System.exit(-1);
    }
}
}

And here is my code to handle each client as connected:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class MultiServer_Client implements Runnable {

public String time;
public Socket client;
public StringBuffer process = new StringBuffer();

public BufferedInputStream inputStream;
public InputStreamReader reader;

public BufferedOutputStream outputStream;
public OutputStreamWriter writer;

public boolean connected = true;

public int ID;

public MultiServer_Client(Socket connection, int i) {
    client = connection;
    ID = i;
    try {
        inputStream = new BufferedInputStream(client.getInputStream());
        reader = new InputStreamReader(inputStream);

        outputStream = new BufferedOutputStream(client.getOutputStream());
        writer = new OutputStreamWriter(outputStream, "US-ASCII");
    } catch (IOException e) {
        System.out.println("IOException: " + e);
    }
    System.out.println("Client connected...");
    write("Connected to " + MultipleSocketServer.name);
}

public void run() {
    while(connected) {
        write("hi");
    }
    System.out.println("Disconnecting client...");
}

public void write(String authen) {
    try {
        time = new java.util.Date().toString();
        String message = time + ": " + authen + (char) 13;
        writer.write(message);
        writer.flush();
    } catch (IOException e) {
        connected = false;
        MultipleSocketServer.connected[ID] = "";
    }
}

public void read() {
    //read from client
    int character;
    process = new StringBuffer();
    try {
        while ((character = reader.read()) != 13) {
            process.append((char) character);
        }
        System.out.println(process);
        process.delete(0, process.length());
    } catch (IOException e) {
        connected = false;
        MultipleSocketServer.connected[ID] = "";
    }
}
}

Srry if I cannot help very much. As I said, I am new to sockets and no one else seems to have any problems with this... Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼趣 2025-01-07 22:01:37

您的代码的问题不在于“套接字”,而在于您的通信协议。在服务器有机会写出“hi”之前,您实际上正在关闭套接字。

要调试此问题,您需要降低程序的复杂性。在您的程序中,有很多事情没有任何意义或无关紧要。

那么,了解一下 Socket 的背景知识。有两种类型的套接字。 “ServerSocket”和“Socket” ServerSocket 有点像秘书。它唯一的工作就是监听呼叫然后将其转接。这就是“接受”的作用。在任何客户端连接之前,accept() 将阻塞,直到收到连接。一旦客户端连接,accept就会返回一个表示连接的Socket。

常规 Socket 是所有工作发生的地方。您可以将其视为电话连接。您可以使用 OutputStream 与远程人员交谈,并使用 InputStream 进行监听。挑战在于您需要为两个套接字创建某种通信(称为协议)来进行通信。

您需要弄清楚如何界定命令。如果您想要一个“长度”分隔协议,您可以传递一个固定长度的数字,然后传递数据,或者您可以使用特殊字符作为消息的结尾(您当前拥有的字符)。为了快速和肮脏,我经常将后者与换行符一起使用。最简单的方法是使用 PrintWriter 进行写入,使用 Scanner 进行读取。

下一步是找出客户端和服务器的通信模式。想一想是否就像来回传球一样。如果客户说了些什么,另一方应该倾听(反之亦然)。

一旦弄清楚协议和逻辑,您就可以将“处理”服务器端的逻辑移动到单独的线程中(称为工作模式),以便服务器一次可以处理多个客户端。如果你想更进一步,你可以实现一个带有线程池的反应器,这样服务器就不会耗尽线程,但这可能是另一天/问题了。

我建议遵循有关套接字的 Java 教程: http://docs.oracle .com/javase/tutorial/networking/sockets/index.html

The problem with your code is not the "sockets" its your communication protocol. You are effectively closing the socket before the server has a chance to write out "hi".

To debug this, you want to reduce the complexity of your program. There are a number of things that don't make any sense or matter in your program.

So, a little background on Sockets. There are two types of sockets. A "ServerSocket" and a "Socket" The ServerSocket is sort of like a secretary. Its only job is to listen for calls and then pass them on. This is what the "accept" does. Before any client connects, the accept() will block until it receives a connection. Once the client connects, the accept returns a Socket representing the connection.

The regular Socket is where all the work occurs. You can think of it as a telephone connection. You can talk to someone remotely with the OutputStream, and listen using the InputStream. The challenge is that you need to create some sort of communication (called a protocol) for your two sockets to communicate.

You need to figure out how you want to delimit your commands. You could pass a fixed length number and then the data if you want a "length" delimited protocol or you could use a special character for the end of the message (what you currently have). For the quick and dirty, I often use the latter with a newline character. The easiest is to just use a PrintWriter for writing and a Scanner for reading.

The next step is to figure out the communication pattern for the client and the server. Think if it as passing a ball back and forth. If the client says something, the other side should be listening (and vice versa).

Once the protocol and logic is figured out, you can then move the logic for "handling" the server side into separate threads (called a worker pattern) so that the server can handle more than one client at a time. If you want to go even further, you can implement a reactor with a thread pool so that the server doesn't run out of threads, but that is probably for another day/question.

I would recommend following the Java tutorial on Sockets: http://docs.oracle.com/javase/tutorial/networking/sockets/index.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文