📄 tcpconnection.java
字号:
package com.zcsoft.opc;
import java.net.*;
import java.io.*;
public class TcpConnection
{
private Socket s;
private OutputStream os;
private BufferedReader is;
/** 每一行头的结尾符 */
private static final byte[] HEADER_TERMINAL = new byte[]{13, 10};
/** 是否写出了所有的头 */
private boolean headerFlushed = false;
TcpConnection(InetAddress host, int port)
throws UnknownHostException, IOException
{
s = new Socket(host, port);
}
void writeHeader(String header) throws IOException
{
byte[] bytes = header.getBytes();
writeHeader(bytes, 0, bytes.length);
}
void writeHeader(byte[] header) throws IOException
{
writeHeader(header, 0, header.length);
}
/**
* 写出一行头信息。该头信息不含结尾标记符<code>\r\n</code>,该方法自行完成该标记的写出动作。
* 该方法并不检查待写入的头信息字节是否以<code>\r\n</code>结尾。
* @param header 头信息字节所在的容器
* @param begin 头信息字节起始位置
* @param length 头信息字节长度
*/
void writeHeader(byte[] header, int begin, int length) throws IOException
{
if (os == null) os = new BufferedOutputStream(s.getOutputStream(), 512);
os.write(header, begin, length);
os.write(HEADER_TERMINAL);
}
/**
* 在写完所有的头信息后,写出头结束写出标记字节,即“\r\n”
* 在调用该方法前一定调用过writeHeader方法,不然该方法将不会向套接字下如任何内容。
*/
void flushHeanders() throws IOException
{
if (os != null && !headerFlushed)
{
os.write(HEADER_TERMINAL);
os.flush();
headerFlushed = true;
}
}
/**
* 读入一行服务程序写回的响应头信息
* @param store 存储头信息的字节容器
* @param begin 从begin位置开始记录头信息的起始字节
* @return 头信息字节长度,不含结束标记\r\n
*/
String readHeader() throws IOException
{
if (is == null)
{
if (!headerFlushed)
{
this.flushHeanders();
}
is = new BufferedReader(new InputStreamReader(s.getInputStream()), 512);
s.shutdownOutput();
}
return is.readLine();
}
void close()
{
try
{
if (os != null)
{
if (!headerFlushed) this.flushHeanders();
os.close();
os = null;
}
if (is != null)
{
is.close();
is = null;
}
}
catch (IOException ex){}
try
{
s.close();
}
catch (IOException ex){}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -