クライアント.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
}
}
サーバー.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
}
}
Server has connected!
サーバーとクライアントの両方から送信したときに、以外に何も起こらないのはなぜ
ですか
s.send("X is online");
反対側で読み取ってコマンドで出力する必要があるのはどれですか?
(bufferreader が printwriter の後にアクティブ化され、それを取得しないためですか?もしそうなら、どうすればこれを修正できますか?)