Java Socket Server端代码示例

2014-05-28 06:30:01 阅读( 257 )

2297人 收藏本页

标签:Java面试题

SocketServer.java类代码

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.log4j.Logger;
import Smart.Java.Com.Constant;
import Smart.Java.Com.StringHandler;
//c:\jdk1.5\bin\java -classpath c:\jdk1.5 SocketServerThread
public class SocketServer {
private static Logger logger = Logger.getLogger(SocketServer.class);

private ServerSocket serverSocket;
private ExecutorService executorService;//线程池
private final int POOL_SIZE=10;//单个CPU线程池大小
public SocketServer(){
try
{
serverSocket = new ServerSocket(Constant.SocketPort);
executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
System.out.println("监听服务器启动,端口号:" + Constant.SocketPort);
}
catch(Exception e)
{
String s = "监听服务器启动 失败,可能是端口" + Constant.SocketPort + "已被占用,请重置端口" + Constant.SocketPort + "后重试";
logger.error(e.getMessage() + "<br />" + s);
//System.out.println();
}
}
public void service() {
try
{
while (true) {
Socket clientSocket=null;
try {
// 接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
clientSocket = serverSocket.accept();
executorService.execute(new SocketHandler(clientSocket));
} catch (Exception e) {
logger.error(StringHandler.GetException(e));
e.printStackTrace();
}
}
}
catch (Exception e1) {
//logger.error(StringHandler.GetException(e1));
//e1.printStackTrace();
}
finally
{
if (serverSocket != null)
{
try
{
serverSocket.close();
}catch(Exception ex1){}
}
}
}
public static void main(String[] args) throws Exception {
try
{
new SocketServer().service();
}
catch(Exception ex)
{
logger.error(StringHandler.GetException(ex));
ex.printStackTrace();
}
}
}

SocketHandler.java类实现代码

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.apache.log4j.Logger;
import Smart.Java.Com.Constant;
import Smart.Java.Com.MonitorHandler;
import Smart.Java.Com.StringHandler;

public class SocketHandler implements Runnable{
private static Logger logger = Logger.getLogger(SocketHandler.class);

private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
}
private PrintWriter getWriter(Socket socket) throws Exception {
OutputStream socketOut = socket.getOutputStream();
return new PrintWriter(socketOut, true);
}

private String GetInfoByAction(String _args)
{
try
{
String returnStr = "";
String[] ssArgs = _args.split(";");
String _productSeries = ssArgs[0];
String _ciKey = ssArgs[1];
if (_productSeries.equals("") || _ciKey.equals(""))
{
return "0";
}
String _ip = ssArgs[2];
String _port = ssArgs[3];
String _username = "";
String _pwd = "";

if (ssArgs.length > 4)
{
_username = ssArgs[4];
if (ssArgs.length > 5)
{
_pwd = ssArgs[5];
}
}

MonitorHandler monitor = new MonitorHandler(_productSeries, _ciKey, _ip, _port, _username, _pwd);

returnStr = monitor.GetMonitorInfo();

return returnStr;
}
catch (Exception e)
{
e.printStackTrace();
logger.error(StringHandler.GetException(e));
return Constant.ErrorNumber_UnkownException;
}
}

private static String GetCurrentTime()
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = formatter.format(cal.getTime());
return time;
}
catch(Exception ex)
{
ex.printStackTrace();
logger.error(StringHandler.GetException(ex));
return "";
}
}
public void run() {
try {
//得到客户端发送的信息
BufferedReader br = null;
InputStream socketIn = socket.getInputStream();

br = new BufferedReader(new InputStreamReader(socketIn));
String actionInfo = "";
try
{
actionInfo = br.readLine();
}
catch(Exception ex){}
while (actionInfo != null)
{
System.out.println(GetCurrentTime() + "收到来自【" + socket.getInetAddress() + ":" + socket.getPort() + "】的监听请求:" + actionInfo);
if (actionInfo != null)
{
String str = GetInfoByAction(actionInfo);
//返回信息给Client端
PrintWriter pw = getWriter(socket);
//System.out.println(str);
pw.println(str);
}
actionInfo = br.readLine();
}
} catch (Exception e) {
logger.error(StringHandler.GetException(e));
e.printStackTrace();
}
finally {
try {
if (socket != null)
socket.close();
} catch (Exception e) {}
}
}
}

下一篇:Velocity 内置指令 #include() 的使用方法

上一篇:Java Socket Server-client端多线程处理代码示例

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题