java网络编程(二)
客户端程序:
package net; import java.io.OutputStream; import java.net.Socket; /** * Created by hu on 2015/11/8. */ public class client { public static void main(String[] args)throws Exception{ connectServer(); } public static void connectServer() throws Exception{ Socket socket=new Socket("127.0.0.1",8089); OutputStream os=socket.getOutputStream(); os.write("my name is hujingwei".getBytes()); //关闭socket的输出流 socket.shutdownOutput(); socket.close(); } }
server端程序:
package net; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; /** * Created by hu on 2015/11/8. */ public class Server { public static void main(String[] args)throws Exception{ ServerSocket server=new ServerSocket(8089); while(true){ acceptClient(server); } } public static void acceptClient(ServerSocket server)throws Exception{ System.out.println("Before accept"); /* * ServerSocket中的accept()方法在没有接收到client的socket的时候,将一直处于阻塞状态(即后面的代码不执行) * 只有当接收到client的一个socket的时候,后面的代码才会继续执行。 * */ Socket socket=server.accept(); System.out.println("After accept"); InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String s=br.readLine(); System.out.println(s); socket.isInputShutdown(); socket.close(); } }