站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Java 专题Echo程序

Echo程序

摘要: Echo程序

</td> </tr> <tr> <td width="522" height="35" valign="top" class="ArticleTeitle"> 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();
}
} </td> <td width="162" valign="top" class="ArticleTeitle">
</td> </tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">


↑返回目录
前一篇: 获取Swing与AWT的版本
后一篇: 压缩文件和目录