用java的net包 模拟C/s

lzmings 发布于 2013/11/06 19:23
阅读 94
收藏 0
配置服务器:
package org.lxh.serverAndClient;
import java.net.*;
import java.io.*;

public class EchoServer {

/**
* @param args
*/
public static void main(String[] args)  throws Exception {
// TODO Auto-generated method stub
  ServerSocket server=new ServerSocket(8888);
  Socket client=null;
  BufferedReader buf=null;
  PrintStream  out=null;
  boolean f=true;
  while(f){
System.out.println("服务器正在运行,等待客户连接。");
client=server.accept();
out=new PrintStream(client.getOutputStream());
buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean  flag=true;
while(flag){

String str=URLDecoder.decode(buf.readLine(), "UTF-8");

if(str==null || "".equals(str))
flag=false;
else
{
System.out.println("运行到这里!");
out.println(URLEncoder.encode("ECHO:"+str,"UTF-8"));
}
}


client.close();

  }
 
 
 


   server.close();
}

}

配置客户端:
package org.lxh.serverAndClient;
import java.net.*;
import java.io.*;

public class EchoClient {
public static void main(String arg[]) throws Exception{
Socket client=new Socket("localhost", 8888);
BufferedReader buf=null;
PrintStream out=null;
BufferedReader input=null;
input=new BufferedReader(new InputStreamReader(System.in));
buf=new BufferedReader(new InputStreamReader(client.getInputStream()));
out=new PrintStream(client.getOutputStream());
boolean flag=true;
while(flag){
System.out.print("输入信息:");
String str=input.readLine();

out.print(URLEncoder.encode(str,"UTF-8"));


if("bye".equals(str))
flag=false;
else
{    System.out.println("输入的字符"+str);
String echo= URLEncoder.encode(buf.readLine(),"UTF-8");
    System.out.println(echo);
}
}
buf.close();
client.close();
}
}

为什么没有什么效果咯,求各位大神帮忙!
加载中
返回顶部
顶部