1 import java.io.PrintStream; 2 import java.net.Socket; 3 import java.net.ServerSocket; 4 import java.util.Scanner; 5 6 public class Server 7 { 8 public static void main(String[] args) 9 throws Exception 10 { 11 ServerSocket ss = new ServerSocket(30000); 12 Socket socket = ss.accept(); 13 PrintStream ps = new PrintStream(socket.getOutputStream()); 14 ps.println("服务器的第一行数据"); 15 ps.println("服务器的第二行数据"); 16 // 关闭socket的输出流,表明输出数据已经结束 17 socket.shutdownOutput(); 18 // 下面语句将输出false,表明socket还未关闭。 19 System.out.println(socket.isClosed()); 20 Scanner scan = new Scanner(socket.getInputStream()); 21 while (scan.hasNextLine()) 22 { 23 System.out.println(scan.nextLine()); 24 } 25 scan.close(); 26 socket.close(); 27 ss.close(); 28 } 29 }
运行上面代码,出现下面错误:
ServerSocket ss = new ServerSocket(30000);//错误在这一行,表明30000端口被占用,原因是可能有程序在占用30000端口,你可以换个端口试一试!