socketserver.java.bak

来自「有关java的源程序,为讲授java程序设计课程使用」· BAK 代码 · 共 62 行

BAK
62
字号
import java.net.*;
import java.io.*;
public class SocketServer
{	public static void main(String args[])
	{	ServerSocket ss=null;
		int port=1000;
		boolean listening=true;
		try
		{ ss=new ServerSocket(port);
		}
		catch(IOException e)
			{   System.err.println("Cannot Listen.");
				System.exit(-1);
			}
		port=ss.getLocalPort();
		System.out.println("Listening on Port:"+port);
		while(listening)
		{  Socket cs=null;
			try
			{ cs=ss.accept();
			}
			catch(IOException e)
			{    System.err.println("Accept failed:"+port);
			     continue;
			}
			new SocketServerThread(cs).start();
		}
		try
		{ ss.close();
		}
		catch(IOException e)
			{ System.err.println("Canot closed server socket.");
			}
	}
}
class SocketServerThread extends Thread
{	Socket s=null;
	SocketServerThread(Socket socket)
	{   super("SocketServerThread");
		s=socket;
	}
	public void run()
	{  try
		{ DataInputStream sin=new DataInputStream(s.getInputStream());
		  PrintStream sout=new PrintStream(s.getOutputStream());	
		  String acceptText;
		  while(true)
		  { if((acceptText=sin.readLine())!=null)
			{	sout.println("Server Message:"+acceptText);
			}
			else
				break;
		  }
		  sout.close();
		  sin.close();
		  s.close();
		}catch(IOException e)
			{ e.printStackTrace();
			}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?