以下是代码服务器:package com.zhang;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;public class InetAddress1 { public static void main(String[] args){ try { ServerSocket serverSocket=new ServerSocket(8888); System.out.println("****服务器即将启动****"); Socket sc=serverSocket.accept(); InputStream is=sc.getInputStream(); InputStreamReader isr=new InputStreamReader(is); BufferedReader br=new BufferedReader(isr); String in=""; while((in=br.readLine())!=null){ System.out.println("服务器:客户端发来的信息是"+in); } System.out.println("111"); sc.shutdownInput(); OutputStream os=sc.getOutputStream(); PrintWriter pw=new PrintWriter(os); pw.write("欢迎光临!"); pw.flush(); os.close(); pw.close(); is.close(); isr.close(); br.close(); sc.close(); } catch (IOException e) { e.printStackTrace(); } }}客户端:package com.zhang;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.Socket;import java.net.UnknownHostException;public class client { /** * @param args */ public static void main(String[] args) { try { Socket socket=new Socket("localhost",8888); OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); pw.write("账户:zxcv200cool 密码:zxcvbnm2008"); pw.flush(); System.out.println("数据发送成功"); InputStream is1=socket.getInputStream(); InputStreamReader isr1=new InputStreamReader(is1); BufferedReader br1=new BufferedReader(isr1); String next=null; while((next=br1.readLine())!=null){ System.out.println("客户端:服务器发来的信息是"+next); } is1.close(); isr1.close(); br1.close(); socket.close(); os.close(); pw.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
1 回答
已采纳
慕圣0830664
TA贡献41条经验 获得超26个赞
在客户端client类中,System.out.println("数据发送成功")前面加上这行代码 socket.shutdownOutput(); 这行代码的意思就是关闭输入流,如果客户端不关闭输入流,服务端不会开始读取信息,它会一直等待。。。等待客户端输入完毕再开始读取。。。
添加回答
举报
0/150
提交
取消