【发布时间】:2017-06-18 05:46:55
【问题描述】:
我正在学习服务器-客户端通信,我做了一个简单的通信器,它可以工作,但我只能向服务器发送一条消息。我不知道如何使从客户端发送和接收更多消息成为可能。我尝试了很多选项,但没有一个可行。
这是我的代码: 客户: 导入 java.io.; 导入 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();
}
}
和服务器:
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();
}
}
【问题讨论】:
标签: java server client communication