指定范围端口的客户端socket 工厂类

7 篇文章 0 订阅

资源: 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));	
		}
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,可以使用多线程编程来实现Java Socket的多线程通信。一种常见的方法是使用Java 5中引入的ExecutorService接口来创建线程池。 首先,在服务端的代码中,可以创建一个线程池,用于处理客户端的请求。通过使用ExecutorService的工厂方法创建一个固定大小的线程池,可以控制并发处理的请求数量。然后,可以使用Socket来监听客户端连接,并将连接交给线程池中的线程来处理。 在每个线程中,可以使用Socket的输入输出流来与客户端进行通信。可以使用BufferedReader来读取客户端发送的请求,并使用PrintWriter来向客户端发送响应。 以下是一个简化的示例代码,用于演示Java Socket的多线程编程: ```java import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Server { public static void main(String[] args) throws IOException { // 创建一个固定大小的线程池 ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建ServerSocket并监听指定端口 ServerSocket serverSocket = new ServerSocket(8888); System.out.println("服务器启动,等待客户端连接..."); while (true) { // 等待客户端连接 Socket socket = serverSocket.accept(); System.out.println("客户端连接成功,地址:" + socket.getInetAddress()); // 将连接交给线程池中的线程来处理 executorService.execute(new ClientHandler(socket)); } } static class ClientHandler implements Runnable { private Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } @Override public void run() { try { // 获取输入输出流 BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); // 读取客户端发送的请求 String request = reader.readLine(); System.out.println("收到客户端请求:" + request); // 处理请求并返回响应 String response = "Hello, " + request + "!"; writer.println(response); System.out.println("发送响应:" + response); // 关闭连接 socket.close(); System.out.println("客户端连接关闭"); } catch (IOException e) { e.printStackTrace(); } } } } ``` 以上代码中,通过创建一个固定大小的线程池,可以控制并发处理的请求数量。每个客户端连接都会被分配给线程池中的一个线程来处理。在每个线程中,读取客户端发送的请求并进行处理,然后将响应发送回客户端。最后,关闭连接。 需要注意的是,以上代码只是一个简化的示例,实际应用中可能需要更复杂的逻辑和异常处理。此外,为了保证线程安全,可能还需要使用同步机制来保护共享资源的访问。 希望以上信息能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值