私はサーバーとクライアントの通信について学んでいます。私は単純なコミュニケータを作っていますが、動作しますが、サーバーには1つのメッセージしか送信できません。私は、クライアントからもっと多くのメッセージを送受信する可能性をどのようにするかを知らない。私はたくさんのオプションを試しましたが、何もしません。java - client - serverクライアントからの複数のメッセージ
ここに私のコードです: クライアント: インポートjava.io. ; import java.net。;
public class Klient
{
public static final int PORT=50007;
public static final String HOST = "127.0.0.1";
public static void main(String[] args) throws IOException
{
Socket sock;
sock=new Socket(HOST,PORT);
System.out.println("communication works: "+sock);
BufferedReader klaw;
klaw=new BufferedReader(new InputStreamReader(System.in));
PrintWriter outp;
outp=new PrintWriter(sock.getOutputStream());
System.out.print("<Sending:> ");
String str=klaw.readLine();
outp.println(str);
outp.flush();
klaw.close();
outp.close();
sock.close();
}
}
とサーバー:
// infinite loop
while (true) {
// ..receive or send commands here..
if (command.equals("exit") {
// exit from loop
}
}
はまた、例外処理を追加します。あなたは例の
を終了するために、あなたのコードや特殊コマンドのメインループを追加する必要が
import java.io.*;
import java.net.*;
public class Serwer
{
public static final int PORT=50007;
public static void main(String args[]) throws IOException
{
ServerSocket serv;
serv=new ServerSocket(PORT);
System.out.println("listen for: "+serv);
Socket sock;
sock=serv.accept();
System.out.println("communication: "+sock);
BufferedReader inp;
inp=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String str;
str=inp.readLine();
System.out.println("<it comes:> " + str);
inp.close();
sock.close();
serv.close();
}
}