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
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 from
Server has connected!
happen when on both I have sent from the server and client
s.send("X is online");
which should be read on the other side and printed out in the cmd?
(is it because the bufferreader is activated after printwriter and doesn't pick it up? if so how can I fix this?)
解决方案
Your BufferedReader#readLine call will block indefinitely unless you send a newline character. Replace
out.print(text);
with
out.println(text);
to match the BufferedReader#readLine calls from both client & server.