socket server-client端通信的例子
程序员文章站
2022-03-02 15:27:30
...
server端例子
public class socketServer {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5678);
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client
.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("server display :has receiv...");
out.flush();
if (str.equals("end"))
break;
}
client.close();
}
}
客户端实例
public class socketClient {
static Socket server;
public static void main(String[] args) throws Exception {
server = new Socket(InetAddress.getLocalHost(), 5678);
BufferedReader in = new BufferedReader(new InputStreamReader(server
.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = wt.readLine();
out.println("client display:"+str);
out.flush();
if (str.equals("end")) {
break;
}
System.out.println(in.readLine());
}
server.close();
}
}
上一篇: 文件通道解析二(文件锁,关闭通道)