TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
import java.io.*;
import java.net.*;
//服务器端
public class EchoServer
{
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
//实例化监听端口
serverSocket = new ServerSocket(1111);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 1111.");
System.exit(1);
}
Socket incoming = null;
while(true)
{
incoming = serverSocket.accept();
out = new PrintWriter(incoming.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
//提示信息
out.println("Hello! . . . ");
out.println("Enter BYE to exit");
out.flush();
//没有异常的情况不断循环
while(true)
{
//只有当有用户输入的时候才返回数据
String str = in.readLine();
//当用户连接断掉时会返回空值null
if(str == null)
{
//退出循环
break;
}
else
{
//对用户输入字串加前缀Echo:
out.println("Echo: "+str);
out.flush();
//退出命令
if(str.trim().equalsIgnoreCase("BYE"))
break;
}
}
//收尾工作
out.close();
in.close();
incoming.close();
serverSocket.close();
}
}
}
import java.io.*;
import java.net.*;
//客户端程序
public class EchoClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try
{
echoSocket = new Socket ( "localhost", 1111);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
}
catch (UnknownHostException e)
{
System.err.println("Don"t know about host: localhost.");
System.exit(1);
}
System.out.println(in.readLine());
System.out.println(in.readLine());
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
//将客户端Socket输入流(既服务器端Socket的输出流)输出到标准输出
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
out.close();
in.close();
echoSocket.close();
}
}
源码下载:http://file.javaxxz.com/2014/9/30/214618156.zip |
|