⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 socketclient.java

📁 Java实现的Socket框架
💻 JAVA
字号:
/**
 * Project:ms4j (Message Server for Java)
 * Date:2007-2-21 
 * Authoer : jobsun@gmail.com
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 */
package com.sunjob.ms4j.client;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;

import com.sunjob.ms4j.util.IOUtil;
import com.sunjob.ms4j.util.PropertyUtil;
import com.sunjob.ms4j.util.XMLBean;

/**
 * @author sunjob
 * 
 */
public class SocketClient {
	// /////////////
	private Socket client = null;

	public SocketClient() throws Exception {
		String useProxy = PropertyUtil.getProperty("ms4j.use.proxy");
		String proxyName = PropertyUtil.getProperty("ms4j.proxy.name");
		String proxyPort = PropertyUtil.getProperty("ms4j.proxy.port");

		String serverName = PropertyUtil.getProperty("ms4j.server.name");
		String serverport = PropertyUtil.getProperty("ms4j.server.port");

		if (useProxy.equalsIgnoreCase("true"))
			client = new Socket(new Proxy(Proxy.Type.SOCKS,
					new InetSocketAddress(proxyName, Integer
							.parseInt(proxyPort))));
		else
			client = new Socket();
		InetSocketAddress isa = new InetSocketAddress(serverName, Integer
				.parseInt(serverport));
		client.connect(isa);
	}

	public void send(String MsgBeanName,Object obj) throws Exception {
		byte[] b = XMLBean.cvtBean2XML(obj);
		OutputStream os = client.getOutputStream();
		os.write(MsgBeanName.getBytes());
		os.write(" ".getBytes());
		os.write(b);
		os.flush();
	}

	public Object request(String MsgBeanName,Object obj) throws Exception {
		byte[] b = XMLBean.cvtBean2XML(obj);
		OutputStream os = client.getOutputStream();
		InputStream is = client.getInputStream();
		os.write(MsgBeanName.getBytes());
		os.write(" ".getBytes());
		os.write(b);
		os.flush();
		
		byte[] bb = IOUtil.read(is);
        Object obj1 = XMLBean.cvtXML2Bean(bb);
		return obj1;
	}

	public void close() throws Exception {
		if (this.client != null && !this.client.isClosed()) {
			this.client.close();
		}
		client = null;
	}

	public static void main(String[] args)
	throws Exception
	{
		SocketClient sc = new SocketClient();
		String s = (String)sc.request("test","test");
		System.out.println(s);
	}
}

⌨️ 快捷键说明

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