问题描述
Client.java
Client.java
package Client;
import java.io.*;
import java.net.*;
class Client {
/*
To send string to server use "out.print(data)"
To use info sent from server use "in.readLine()"
*/
int port = 1234;
String hostname = "localhost";
String input,output;
public void send(String text) {
try {
Socket skt = new Socket(hostname, port); /*Connects to server*/
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream())); /*Reads from server*/
System.out.println("Server:" + in.readLine());
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.print(text); /*Writes to server*/
skt.close();
out.close(); /*Closes all*/
in.close();
}
catch(Exception e) {
System.out.print("Error Connecting to Server\n");
}
}
public static void main(String args[]) {
Client c = new Client();
c.send("Server is online"); //sends message to server
}
}
Server.java
Server.java
package Server;
import java.io.*;
import java.net.*;
class Server {
/*
To send string to client use "out.print(data)"
To use info sent from client use "in.readLine()"
*/
int port = 1234;
String input,output;
public void send(String text) {
try {
ServerSocket srvr = new ServerSocket(port);
Socket skt = srvr.accept(); /*Waiting for Connection from client*/
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
out.print(text); /*Write/Send to Client*/
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream())); /*Read from Client*/
System.out.println("Client:" + in.readLine());
out.close();
in.close();
skt.close(); /*Closes all*/
srvr.close();
} catch( Exception e) {
System.out.print("Error Connecting\n");
}
}
public static void main(String args[]) {
Server s = new Server();
s.send("Client is online"); //sends a message to client
}
}
为什么除了
服务器已连接之外,什么都没做!
发生在我从服务器和客户端发送过来的情况下
why does nothing apart fromServer has connected!
happen when on both I have sent from the server and client
s.send("X is online");
应该在另一面阅读并在cmd中打印出来吗?
which should be read on the other side and printed out in the cmd?
(是因为bufferreader在printwriter之后被激活并且没有拾取?如果可以的话,我该如何解决?)
(is it because the bufferreader is activated after printwriter and doesn't pick it up? if so how can I fix this?)
推荐答案
除非您发送换行符,否则您的 BufferedReader#readLine
调用将无限期阻塞。替换
Your BufferedReader#readLine
call will block indefinitely unless you send a newline character. Replace
out.print(text);
与
out.println(text);
匹配来自以下位置的 BufferedReader#readLine
调用客户和服务器。
to match the BufferedReader#readLine
calls from both client & server.
这篇关于Java客户端/服务器读取和写入不起作用,也没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!