81,092
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.net.*;
public class EchoServer
{
private int port=8000;
private ServerSocket svSocket;
public EchoServer() throws IOException
{
ServerSocket svSocket=new ServerSocket(port);
System.out.println("服务器启动!");
}
public String echo(String msg){
return "echo: "+msg;
}
private PrintWriter getWriter(Socket sk) throws IOException{
OutputStream out=sk.getOutputStream();
return new PrintWriter(out,true);
}
private BufferedReader getReader(Socket sk) throws IOException{
InputStream in=sk.getInputStream();
return new BufferedReader(new InputStreamReader(in));
}
public void service()
{
while(true)
{
Socket sk=null;
try
{
sk=svSocket.accept(); //通过使用输出语句测试好像是这里抛出了异常
System.out.println("new connection accepted: "+sk.getInetAddress()+":"+sk.getPort());
BufferedReader br=getReader(sk);
PrintWriter pw=getWriter(sk);
String msg=null;
while((msg=br.readLine())!=null)
{
System.out.println(msg);
pw.println(echo(msg));
if(msg.equals("bye"))
{
break;
}
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if(sk!=null)
sk.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
}
public static void main(String [] args) throws IOException
{
System.out.println("hello");
new EchoServer().service();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class EchoClient{
private String host="localhost";
private int port=8000;
private Socket sk;
public EchoClient() throws IOException{
sk=new Socket(host,port);
}
public static void main(String[] args) throws IOException{
new EchoClient().talk();
}
private PrintWriter getWriter(Socket sk) throws IOException{
OutputStream out=sk.getOutputStream();
return new PrintWriter(out,true);
}
private BufferedReader getReader(Socket sk) throws IOException{
InputStream in=sk.getInputStream();
return new BufferedReader(new InputStreamReader(in));
}
public void talk() throws IOException{
try{
BufferedReader br=getReader(sk);
PrintWriter pw=getWriter(sk);
BufferedReader localReader=new BufferedReader(new InputStreamReader(System.in));
String msg=null;
while((msg=localReader.readLine())!=null){
pw.println(msg);
System.out.println(br.readLine());
if(msg.equals("bye"))
break;
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
sk.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}