import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 我的Socket类.
 * 
 * 封装JDK内置Socket,提供收发消息等功能.
 * 
 * @author weep
 */
public class MySocket {
	private Socket socket = null;
	private PrintStream printStream;
	private BufferedReader bufferedReader;
	private BufferedReader bufferedKeyReader;
	
	public MySocket() throws UnknownHostException, IOException {
		this("127.0.0.1", 8000);
	}

	public MySocket(Socket socket) {
		super();
		this.socket = socket;
	}

	public MySocket(String serverIp, int port) throws UnknownHostException, IOException {
		super();
		socket = new Socket(serverIp, port);
	}
	
	public void send(String msg) throws IOException {
		if (null == printStream) {
			printStream = new PrintStream(socket.getOutputStream());
		}
		
		printStream.println(msg);
	}
	
	public String receive() throws IOException {
		if (null == bufferedReader) {
			bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		}
		
		return bufferedReader.readLine();
	}
	
	public String readKey() throws IOException {
		if (null == bufferedKeyReader) {
			bufferedKeyReader = new BufferedReader(new InputStreamReader(System.in));
		}
		
		return bufferedKeyReader.readLine();
	}
	
	public String getIp() {
		return socket.getInetAddress().getHostAddress();
	}
	
	public void close() {
		if (null == socket)
			return;
		
		try {
			socket.close();
		} catch (IOException e) {
		}
	}
}
最近下载更多
buhuia  LV4 2023年6月7日
linmou  LV8 2023年3月19日
dyrcl01  LV1 2021年7月16日
最后的低调~  LV1 2021年7月8日
2842539  LV1 2021年7月7日
哈七  LV1 2021年6月25日
ꪶꪮꪰꪤꫀ⅓¼  LV1 2021年6月7日
D  LV1 2021年5月13日
mewgulf  LV1 2020年12月2日
小小先生啊  LV4 2020年11月24日
最近浏览更多
dapeng0011  LV15 7月18日
Ji123455  LV8 2023年9月21日
cksndh  LV4 2023年8月16日
yybb7435100  LV2 2023年8月7日
buhuia  LV4 2023年6月7日
林间听风  LV10 2023年4月7日
linmou  LV8 2023年3月19日
gzryue  LV6 2023年3月8日
heqian  LV16 2023年1月10日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友