资源: http://download.csdn.net/detail/AFer198215/3647106 中的部分代码,用于创建指定端口范围内的客户端Socket连接。
package org.sl.net.client;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Random;
import org.apache.log4j.Logger;
import org.sl.net.util.Configure;
import org.sl.util.Utility;
/**
* 客户端连接工厂
* @author sl
*
*/
public class ClientFactory {
private static final Logger logger = Logger.getLogger(ClientFactory.class);
private byte[] buffer = new byte[8];
private String localHost;
private int minPort;
private int maxPort;
private String remoteIp;
private int remotePort;
/**
* 返回一个在指定端口范围内的已建立连接的client socket
* @param command 命令号
* @return
* @exception IOException
*/
// synchronized static
public Socket getClient(int command) throws IOException{
// int minPort = 0;
// int maxPort = 0;
Socket client = null;
// String localHost = null;
int localPort = 0;
// String remoteIp = null;
// int remotePort = 0;
InetSocketAddress remoteAddress = null;
InetSocketAddress localAddress = null;
Random random = new Random();
int testCount = 0;
// minPort = Integer.parseInt(Configure.getParameter("local.port.client.min"));
// maxPort = Integer.parseInt(Configure.getParameter("local.port.client.max"));
testCount = (maxPort-minPort)/2+10;
// remoteIp = Configure.getParameter("remote.ip");
// remotePort = Integer.parseInt(Configure.getParameter("remote.port"));
remoteAddress = new InetSocketAddress(remoteIp, remotePort);
// localHost = Configure.getParameter("local.ip");
for(int i = 1;; i++){
random.setSeed(System.currentTimeMillis());
localPort = random.nextInt(maxPort-minPort)+minPort;
localAddress = new InetSocketAddress(localHost, localPort);
try{
client = new Socket();
client.bind(localAddress);
client.connect(remoteAddress, 1000*60);//1分钟超时
if(!client.isConnected()){//如果此client不可用
if(null != client) client.close();
}else{
//发送请求头
// System.arraycopy(Configure.REQUEST_HEADER, 0, buffer, 0, 4);
// System.arraycopy(Utility.int2Byte(command), 0, buffer, 4, 4);
// client.getOutputStream().write(buffer);
Utility.int2Byte(command, buffer, 0);
client.getOutputStream().write(Configure.REQUEST_HEADER);
client.getOutputStream().write(buffer, 0, 4);
client.getOutputStream().flush();
break;
}
}catch(BindException ex){
try{
if(null != client) client.close();
}catch(Exception ex1){
}
if(i >= testCount){
logger.error("大量端口被占用,端口无法绑定.");
throw new RuntimeException("大量端口被占用,端口无法绑定.");
}
}
try {
Thread.sleep(7);
} catch (InterruptedException e) {
}
}
return client;
}
public void setMinPort(int minPort) {
this.minPort = minPort;
}
public void setMaxPort(int maxPort) {
this.maxPort = maxPort;
}
public void setRemoteIp(String remoteIp) {
this.remoteIp = remoteIp;
}
public void setRemotePort(int remotePort) {
this.remotePort = remotePort;
}
public void setLocalHost(String localHost) {
this.localHost = localHost;
}
}
package org.sl.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring IoC工具
* @author sl
*
*/
public class SpringTool {
private static ApplicationContext ctx = null;
/**
* 返回一个应用容器
* @return
*/
synchronized
public static ApplicationContext getAppContext() {
if (null == ctx) {
ctx = new ClassPathXmlApplicationContext(
new String[] { "/transmit.spring.xml" });
}
return ctx;
}
/**
* 依据容器的数据,返回一个范型的类实例
* @param <T> 类
* @param name bean名
* @return
*/
@SuppressWarnings("unchecked")
synchronized
static public <T> T getBean(String name){
return (T) getAppContext().getBean(name);
}
}
transmit.spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"
>
<bean id="clientFactory"
class="org.sl.net.client.ClientFactory"
autowire="byName">
<property name="localHost">
<value>192.168.2.23</value>
</property>
<property name="minPort">
<value>8100</value>
</property>
<property name="maxPort">
<value>8300</value>
</property>
<property name="remoteIp">
<value>192.168.2.23</value>
</property>
<property name="remotePort">
<value>8401</value>
</property>
</bean>
<bean id="transmitServer"
class="org.sl.net.server.TransmitServer"
autowire="byName">
<property name="localHost">
<value>192.168.2.23</value>
</property>
<property name="listenerPort">
<value>8401</value>
</property>
</bean>
<bean id="threadPool"
class="org.sl.util.ThreadPool"
autowire="byName"
scope="prototype"
init-method="createPool">
<property name="capacity">
<value>200</value>
</property>
</bean>
<bean id="connectFilter"
class="org.sl.net.server.ConnectFilter"
autowire="byName"
scope="prototype">
<property name="timeout">
<value>5000</value>
</property>
</bean>
<bean id="testResponsetHandler"
class="org.sl.net.server.service.impl.TestResponsetHandler"
autowire="no"
scope="prototype">
</bean>
<bean id="downloadResponsetHandler"
class="org.sl.net.server.service.impl.DownloadResponsetHandler"
autowire="no"
scope="prototype">
</bean>
</beans>
测试类:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import org.sl.net.RequestCommand;
import org.sl.net.client.ClientFactory;
import org.sl.net.util.Configure;
import org.sl.util.SpringTool;
import org.sl.util.Utility;
public class ClientFactoryTest{
public static void main(String [] args){
// t1();
// t2();
// t3();
// t4();
t5();
}
static void t5(){
byte[] buffer = new byte[1000];
int readLen = 0;
Socket c = null;
ClientFactory cf = SpringTool.getBean("clientFactory");
InputStream in = null;
OutputStream out = null;
// String file = "D:\\test\\1\\1234.txt";
String file = "d:\\test\\1\\中文.txt";
File storeFile = new File("d:\\test\\2", "clone.txt");
OutputStream fileOut = null;
byte[] bs = null;
try {
c = cf.getClient(RequestCommand.DOWNLOAD);
in = c.getInputStream();
out = c.getOutputStream();
bs = file.getBytes(RequestCommand.CHARSET_ENCODING);
out.write(Utility.int2Byte(bs.length));
// out.write(new byte[]{0x0, 0x0, 0x0, 0x3});
out.write(bs);
out.write(Utility.long2Byte(0L));
out.flush();
fileOut = new FileOutputStream(storeFile);
while(-1 != (readLen = in.read(buffer))){
fileOut.write(buffer, 0, readLen);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(null != fileOut) fileOut.close();
}catch(Exception ex){
}
try{
c.close();
}catch(Exception ex){
}
}
}
static void t4(){
// Configure.loadConfigure("src/transmit-configure.xml");
Socket c = null;
byte[] buffer = new byte[512];
int readLen = 0;
InputStream in = null;
ClientFactory cf = SpringTool.getBean("clientFactory");
for(int i = 1; i <= 100; i++){
try {
c = cf.getClient(RequestCommand.TEST);
in = c.getInputStream();
for(int j = 0; in.available() < 0; j++){
Thread.sleep(10);
if(j >= 10){
System.out.println("client:" + i + " msg: --null--");
System.exit(0);
}
}
readLen = in.read(buffer);
System.out.println("client:" + i + " msg:" + new String(buffer, 0, readLen));
// Thread.sleep(100);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try{
c.close();
}catch(Exception ex){
}
}
}
}
static void t3(){
Configure.loadConfigure("src/transmit-configure.xml");
// for(int i = 0; i < 50; i++){
// System.out.println(ClientFactory.getNotBindPort("192.168.2.23"));
// }
}
static void t2(){
Configure.loadConfigure("src/transmit-configure.xml");
// for(int i = 0;i < 20; i++){
// System.out.println(ClientFactory.getPort());
// }
}
static void t1(){
int[] ports = {
80,
8099,
10000,
23,
22,
8771,
};
for(int port: ports){
// System.out.println("port:"+port+" " +ClientFactory.notExistBind("192.168.2.23", port));
}
}
}