Socket基础(一)
Socket基础(1)
打开两个控制台分别运行后(先开服务器,再开客户端),会在服务器端的控制台上输出"Hello Server",客户端的控制台上输出"Hello Client"
/* 服务器端代码 2013/3/21 星期四 10:51:02 */ import java.net.*; import java.io.*; public class TCPServer{ public static void main(String[] args)throws Exception{ //实例化ServerSocket对象 ,使用8800端口进行连接 ServerSocket serverSocket = new ServerSocket(8800); //死循环,无限接受Socket连接 while(true){ //使用阻塞式的accept()方法接受Socket连接; Socket socket = serverSocket.accept(); //getInputStream()方法返回InputStream对象 DataInputStream dis = new DataInputStream(socket.getInputStream()); String s = dis.readUTF(); System.out.println(s); //像客户端输出信息 OutputStream os = socket.getOutputStream(); DataOutputStream bos = new DataOutputStream(os); bos.writeUTF("Hello Client"); dis.close(); os.close(); bos.flush(); bos.close(); } } } /* 客户端代码 2013/3/21 星期四 10:51:34 */ import java.net.*; import java.io.*; public class TCPClient{ public static void main(String[] args)throws Exception{ //实例化一个客户端,连接到IP地址为"127.0.0.1"的计算机的8800端口 Socket socket = new Socket("127.0.0.1",8800); //Socket类的getOutputStream()方法返回值为一个OutputStream对象 OutputStream os = socket.getOutputStream(); DataOutputStream bos = new DataOutputStream(os); bos.writeUTF("Hello Server"); DataInputStream dis = new DataInputStream(socket.getInputStream()); String s = dis.readUTF(); System.out.println(s); os.close(); bos.flush(); bos.close(); dis.close(); } }
打开两个控制台分别运行后(先开服务器,再开客户端),会在服务器端的控制台上输出"Hello Server",客户端的控制台上输出"Hello Client"