首页 > 代码库 > Java网络编程(ECHO案列)
Java网络编程(ECHO案列)
//服务器端
package org.tcp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args) throws Exception{
ServerSocket server = null;
Socket client = null;
PrintStream out = null;
BufferedReader buf = null;
server = new ServerSocket(8888);
boolean f = true;
while(f){
System.out.println("服务器运行,等待客户端链接。");
client = server.accept();
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintStream(client.getOutputStream());
boolean flag = true;
while(flag){
String str = buf.readLine();
if(str == null||"".equals(str)){
flag = false;
}else{
if("bye".equals(str)){
flag = false;
}else{
out.println("ECHO:"+str);
}
}
}
out.close();
client.close();
}
server.close();
}
}
程序运行结果: 服务器运行,等待客户端链接。
//客户端
package org.tcp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class EchoClient {
public static void main(String[] args) throws Exception{
Socket client = null;
client = new Socket("localhost",8888);
BufferedReader buf = null;
PrintStream out = null;
BufferedReader input = null;
input = new BufferedReader(new InputStreamReader(System.in));
out = new PrintStream(client.getOutputStream());
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean flag = true;
while(flag){
System.out.print("输入信息:");
String str = input.readLine();
out.println(str);
if("bye".equals(str)){
flag = false;
}else{
String echo = buf.readLine();
System.out.println(echo);
}
}
client.close();
buf.close();
}
}
程序运行结果: 输入信息:陈飞鹏
ECHO:陈飞鹏
输入信息:chenfeipeng
ECHO:chenfeipeng
输入信息:hello
ECHO:hello
输入信息:bye