慕盖茨7610259
2016-02-24 12:40
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import javax.print.attribute.standard.Severity; public class ServeTest { /**服务器端 * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { ServerSocket socket=new ServerSocket(8888); System.out.println("****服务器启动,正在等待客户端连接****"); Socket s=socket.accept(); InputStream is=s.getInputStream(); InputStreamReader isr=new InputStreamReader(is); BufferedReader br=new BufferedReader(isr); String info =null; while((info=br.readLine())!=null){ System.out.println("我是服务器,客户端说"+info); } OutputStream os=s.getOutputStream(); PrintWriter pw=new PrintWriter(os); pw.write("欢迎您"); pw.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class SocketTest { /**客户端 * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { //1.创建客户端Socket,指定服务器地址和端口 Socket s=new Socket("WIN-M4K2FSPKJ4I",8888); //2.获取输出流,向服务器端发送信息 OutputStream opt=s.getOutputStream(); //将输出流包装为打印流 PrintWriter pw=new PrintWriter(opt); pw.write("用户名:admin 密码 :123"); pw.flush(); //3.获取输入流,并读取服务器端的响应信息 InputStream is= s.getInputStream(); BufferedReader br1=new BufferedReader(new InputStreamReader(is));//装换为字符流 String info=null; //(提示这里出错) while((info=br1.readLine())!=null){ System.out.println("我是客户端,服务器说:"+info); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
你试试关闭这些流试试,即close
Java Socket应用---通信是这样练成的
125013 学习 · 590 问题
相似问题