欢迎来到虫虫下载站 | 资源下载 资源专辑 关于我们
虫虫下载站

socketserver.java

有关java的源程序,为讲授java程序设计课程使用
JAVA
字号:
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);
//				system.println("Server Message:"+acceptText);
			}
			else
				break;
		  }
		  sout.close();
		  sin.close();
		  s.close();
		}catch(IOException e)
			{ e.printStackTrace();
			}
	}
}

⌨️ 快捷键说明

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