자바 소켓 장 연결 예제 코드
20727 단어 J2SE
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration.ConfigurationException;
import org.directwebremoting.impl.DaemonThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.shihuan.dragonkeeper.common.utils.PropertiesUtil;
import com.shihuan.dragonkeeper.global.ConfigFile;
public class SocketListenerPusher implements Runnable {
protected static Logger logger = LoggerFactory.getLogger(SocketListenerPusher.class);
public static String socketlistenerserver_CONFIG = ConfigFile.SOCKETLISTENERSERVER__CONFIG + ConfigFile.SUFFIX_NAME;
private ServerSocket serverSocket;
private ExecutorService pool;
public SocketListenerPusher() {
int port = 0;
int poolsize = 0;
try {
port = Integer.parseInt(PropertiesUtil.getPropertiesValue(socketlistenerserver_CONFIG, "serverport"));
poolsize = Integer.parseInt(PropertiesUtil.getPropertiesValue(socketlistenerserver_CONFIG, "poolsize"));
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(port));
pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * poolsize);
// run() , while(true){...}
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, new DaemonThreadFactory());
executor.scheduleAtFixedRate(this, 1L, 1L, TimeUnit.MILLISECONDS);
} catch (NumberFormatException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
} catch (ConfigurationException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
} catch (IOException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
public void run() {
Socket socket = null;
try {
socket = serverSocket.accept();
pool.execute(new SocketListenerHandler(socket));
} catch (IOException e) {
System.out.println(" !!!!!!!!!!!");
pool.shutdown();
logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
SocketListener Handler. java 코드 는 다음 과 같 습 니 다.
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.io.IOUtils;
import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSessions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.shihuan.dragonkeeper.common.dto.DataSourceInfo;
import com.shihuan.dragonkeeper.common.utils.ByteArrayUtil;
import com.shihuan.dragonkeeper.common.utils.DataSourceMapUtil;
import com.shihuan.dragonkeeper.common.utils.DateFormatterUtil;
import com.shihuan.dragonkeeper.common.utils.PropertiesUtil;
import com.shihuan.dragonkeeper.global.ConfigFile;
import com.shihuan.dragonkeeper.server.bean.ActivityServiceBean;
public class SocketListenerHandler implements Runnable {
protected static Logger logger = LoggerFactory.getLogger(SocketListenerHandler.class);
private static String jdbc_CONFIG = ConfigFile.JDBC_CONFIG + ConfigFile.SUFFIX_NAME;
public static final int timeOut = 0*1000 ; // 1
private final String dataRealTimeAction_id = "Agentdata_" + Math.random();
private static final String noData = "{'nodata':' '}";
private static final String errorData = "{'error':' '}";
private Socket connectedsocket = null;
public SocketListenerHandler(Socket socket){
this.connectedsocket = socket;
}
@Override
public void run() {
BufferedReader in = null;
String resultData = "";
try {
connectedsocket.setSoTimeout(timeOut); // , . , read() SocketTimeoutException , Socket , , , 0( , )
connectedsocket.setKeepAlive(false); // Socket, .
in = new BufferedReader(new InputStreamReader(connectedsocket.getInputStream()));
if (in.ready()) { //
resultData = getNoHeadData(in.readLine()); // Agent
logger.info("#### DATA = "+resultData);
if (resultData==null || "".equals(resultData)) {
logger.info(dataRealTimeAction_id + " -->>> " + " !");
} else if (resultData.charAt(0) != '{') { //
logger.info(dataRealTimeAction_id + " -->>> " + noData);
} else {
ActivityServiceBean asb = JSON.parseObject(resultData, ActivityServiceBean.class);
System.out.println(" Start......");
System.out.println(asb.getProxyname() + " -- " + asb.getIp() + " -- " + asb.getCalltime() + " -- " + asb.getAnswertime() + " -- " + asb.getCpu() + " -- " + asb.getThread() + " -- " + asb.getStatus() + " -- " + asb.getAccessaddress() + " -- " + asb.getAccessfilename() + " -- " + asb.getSql() + " -- " + asb.getContent());
System.out.println(" End......");
// parseData(ois);
logger.info(dataRealTimeAction_id + ": !");
}
}
} catch (IOException e) {
logger.error(e.getMessage() + " " + errorData, e);
e.printStackTrace();
} catch (NumberFormatException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
}
}
TestSocketListener Pusher. java 요청 단 코드 는 다음 과 같 습 니 다.
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import org.apache.commons.configuration.ConfigurationException;
import com.alibaba.fastjson.JSON;
import com.shihuan.dragonkeeper.common.utils.ByteArrayUtil;
import com.shihuan.dragonkeeper.common.utils.PropertiesUtil;
import com.shihuan.dragonkeeper.global.ConfigFile;
import com.shihuan.dragonkeeper.server.bean.ActivityServiceBean;
public class TestSocketListenerPusher implements Runnable {
private static String socketlistenerserver_CONFIG = ConfigFile.SOCKETLISTENERSERVER__CONFIG + ConfigFile.SUFFIX_NAME;
private Socket socketclient = null;
@Override
public void run() {
String serverip = "";
int port = 0;
OutputStream os = null;
try {
serverip = PropertiesUtil.getPropertiesValue(socketlistenerserver_CONFIG, "serverip");
port = Integer.parseInt(PropertiesUtil.getPropertiesValue(socketlistenerserver_CONFIG, "serverport"));
ActivityServiceBean asb = null;
for (int i=0; i<2; i++) {
asb = new ActivityServiceBean();
asb.setProxyname("testProxyname"+i);
asb.setIp("testIp"+i);
Date curdate = new Date();
asb.setCalltime(curdate);
asb.setAnswertime(curdate);
asb.setCpu("testCpu"+i);
asb.setThread("testThread"+i);
asb.setStatus("testStatus"+i);
asb.setAccessaddress("testAccessaddress"+i);
asb.setAccessfilename("testAccessfilename"+i);
asb.setSql("testSql"+i);
asb.setContent("testContent"+i);
String jsonStr = JSON.toJSONString(asb).trim();
byte[] information = (new String(ByteArrayUtil.getIntToByte(jsonStr.length()))+jsonStr).getBytes();
System.out.println(information.length);
socketclient = new Socket(serverip, port);
socketclient.setSoTimeout(0);
socketclient.setKeepAlive(false);
os = new BufferedOutputStream(socketclient.getOutputStream());
os.write(information);
os.flush();
System.out.println("Client" + i + " -->>> " + new String(ByteArrayUtil.getIntToByte(jsonStr.length()))+jsonStr);
os.close();
Thread.sleep(3000);
}
} catch (ConfigurationException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
/*
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
*/
}
}
public static void main(String[] args) {
Thread t = new Thread(new TestSocketListenerPusher());
t.start();
}
}
원본 코드[email protected]메 일 박스 의 J2EE 코드 폴 더 에 있 습 니 다.
----------------------------------------------------------------------------------
byte [] 에 따라 데 이 터 를 전송 하 는 경우 다음 코드 를 참고 하 십시오.
SimpleSocketServer. java 코드 는 다음 과 같 습 니 다.
package com.shihuan.socket;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleSocketServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true); // , ,
ss.setReceiveBufferSize(128*1024); // , 8192
ss.bind(new InetSocketAddress(19990));
Socket client = ss.accept();
InputStream in = new BufferedInputStream(client.getInputStream());
byte tmpb = (byte)in.read();
System.out.println(" byte --->> " + tmpb);
System.out.println(" --->> " + in.available());
byte[] bc = new byte[in.available()+1];
bc[0] = tmpb;
in.read(bc, 1, in.available());
System.out.println(bc.length);
System.out.println(new String(bc));
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
SimpleSocketClient. java 코드 는 다음 과 같 습 니 다.
package com.shihuan.socket;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SimpleSocketClient {
public static void main(String[] args) throws UnknownHostException {
try {
Socket s = new Socket("192.168.1.10", 19990);
OutputStream os = new BufferedOutputStream(s.getOutputStream());
String info = "abc!";
info = " !";
byte[] bi = info.getBytes();
os.write(bi);
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
조금 복잡 한 코드 예제 로 접착 문 제 를 처리 하 였 습 니 다.
StartListenerTcpThread. java 코드:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Vector;
import java.util.concurrent.ExcutorService;
import java.util.concurrent.Excutors;
import org.apache.commons.io.IUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.shihuan.dragonkeeper.common.utils.ByteArrayUtil;
import com.shihuan.dragonkeeper.global.ConfigFile;
public class StartListenerTcpThread implements Runnable {
public static Logger logger = LoggerFactory.getLogger(StartListenerTcpThread.class);
private static ExcutorService Threadpool = Excutors.newCachedThreadPool();
private static boolean businessflag = true;
private static final int receiveBufferSize = 128;
private static Vector tmpbytes = new Vector();
private ServerSocket serverSocket = null;
public StartListenerTcpThread(String ip, int port){
try{
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.setReceiveBufferSize(receiveBufferSize*1024);
serverSocket.setSoTimeout(0);
SocketAddress sa = new InetSocketAddress(port);
serverSocket.bind(sa, 20);
}catch(IOException e){
logger.error(e.getMessage(), e);
}
}
public void run(){
Socket socket = null;
while(true){
if(businessflag){
try{
socket = serverSocket.accept();
System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
InputStream socketIn = new BufferedInputStream(socket.getInputStream());
byte tmpb = (byte)socketIn.read();
byte[] currentbytes = null;
if(tmpbytes.size() > 0){ // IO
int oldBytesLen = tmpbytes.get(0).length;
int socketBytesLen = socketIn.available()+1;
int currentLength = oldByteLen + socketBytesLen;
currentbytes = new byte[currentLength];
System.arraycopy(tmpbytes.get(0), 0, currentbytes, oldBytesLen);
currentbytes[oldBytesLen] = tmpb;
socketIn.read(currentbytes, oldBytesLen+1, socketBytesLen-1);
socketIn.close();
splitInputStreamByte(currentbytes);
}else{ //
int socketBytesLen = socketIn.available()+1;
currentbytes = new byte[socketBytesLen];
currentbytes[0] = tmpb;
socketIn.read(currentbytes, 1, socketBytesLen-1);
socketIn.close();
splitInputStreamByte(currentbytes);
}
}catch(IOException e){
logger.error(e.getMessage(), e);
}
}
}
}
/**
* byte
* @param parambytes byte
* @return byte
*/
private static void splitInputStreamByte(byte[] parambytes) {
if(parambytes != null){
if(parambytes.length > 4){
byte[] head = new byte[4]; //
System.arraycopy(parambytes, 0, head, 0, 4);
int bodyLength = ByteArrayUtil.getint(head);
if(bodyLength <= parambytes.length-4){
final byte[] body = new byte[bodyLength];
System.arraycopy(parambytes, 4, body, 0, bodyLength);
ThreadPool.execute(new Runnable(){
public void run(){
byte[] processDatas = body;
try{
System.out.println(IOUtils.toString(processDatas, "UTF-8").trim());
}catch(IOException e){
logger.error(e.getMessage(), e);
}
}
});
int resultLen = parambytes.length-4-bodyLength;
if(resultLen == 0){
splitInputStreamByte(null);
}else{
byte[] resultbytes = new byte[resultLen];
System.arraycopy(parambytes, 4+bodyLength, resultbytes, 0, resultLen);
splitInputStreamByte(resultbytes);
}
}else{
tmpbytes.clear();
tmpbytes.add(parambytes);
}
}else{
tmpbytes.clear();
tmpbytes.add(parambytes);
}
}
}
public static void openflag(){
businessflag = true;
}
public static void closeflag(){
businessflag = false;
}
}
TestTcpSocket. java 코드:
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import com.shihuan.dragonkeeper.common.utils.ByteArrayUtil;
import com.shihuan.dragonkeeper.global.ConfigFile;
public class TestTcpSocket implements Runnable{
private Socket socketClient = null;
public void run(){
String serverip = "192.168.1.10";
int port = 19990;
try{
while(true){
System.out.println("SocketClient start......");
String mystr = "hello everyone!";
socketClient = new Socket(serverip, port);
OutputStream os = socketClient.getOutputStream();
byte[] head = ByteArrayUtil.int2byte(mystr.length());
byte[] body = mystr.getBytes();
byte[] total = ByteArrayUtil.byteMerge(head, body);
os.write(total);
os.flush();
os.close();
Thread.sleep(1000);
System.out.println("SocketClient end......");
}
}catch(Exception e){
logger.error(e.getMessage(), e);
}
}
public static void main(String[] args){
Thread t = new Thread(new TestTcpSocket());
t.start();
}
}
다음은 ByteArray Util. java 코드 입 니 다.
package com.shihuan.dragonkeeper.common.utils;
public class ByteArrayUtil {
/**
* int byte[]
*/
public static final byte[] int2byte(int paramInt){
byte[] resultByte = new byte[4];
resultByte[3] = ((byte)(paramInt & 0xFF));
resultByte[2] = ((byte)(paramInt >>> 8 & 0xFF));
resultByte[1] = ((byte)(paramInt >>> 16 & 0xFF));
resultByte[0] = ((byte)(paramInt >>> 24 & 0xFF));
return resultByte;
}
/**
* byte int
*/
public static final int getint(byte[] paramArrayOfByte){
int result = (paramArrayOfByte[0] & 0xFF) << 24 | (paramArrayOfByte[1] & 0xFF) << 16 | (paramArrayOfByte[2] & 0xFF) << 8 | paramArrayOfByte[3] & 0xFF;
return result;
}
/**
* byte byte
*/
public static byte[] byteMerge(byte[] byte1, byte[] byte2){
byte[] result = new byte[byte1.length+byte2.length];
System.arraycopy(byte1, 0, result, 0, byte1.length);
System.arraycopy(byte2, 0, result, byte1.length, byte2.length);
return result;
}
}
[url]http://blog.csdn.net/defonds/article/details/8782785[/url]
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JMX의 간단한 회고전에 JMX에 대해 알아봤는데 업무 중에 가끔 사용하기도 해요. 그런데 어떤 것을 체계적으로 배우지 않으면 마음이 공허해요. 그래서 이틀 동안 정돈을 했어요.코드를 좀 넣으세요. JMX규범의 구조도와 함께. JMX ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.