二
Socket選擇可以指定Socket類發送和接受數據的方式
public final static int TCP_NODELAY =
public final static int SO_REUSEADDR =
public final static int SO_LINGER =
public final static int SO_TIMEOUT =
public final static int SO_SNDBUF =
public final static int SO_RCVBUF =
public final static int SO_KEEPALIVE =
public final static int SO_OOBINLINE =
有趣的是
public boolean getTcpNoDelay() throws SocketException
public void setTcpNoDelay(boolean on) throws SocketException
在默認情況下
這種算法雖然可以有效地改善網絡傳輸的效率
public boolean getReuseAddress() throws SocketException
public void setReuseAddress(boolean on) throws SocketException
通過這個選項
這種處理機制對於隨機綁定端口的Socket對象沒有什麼影響
package mynet;
import
import java
public class Test
{
public static void main(String[] args)
{
Socket socket
Socket socket
try
{
socket
socket
System
+ socket
socket
}
catch (Exception e)
{
System
try
{
socket
socket
System
+ socket
System
}
catch (Exception e
{
System
}
}
}
}
上面的代碼的運行結果如下
socket
error:Address already in use: JVM_Bind
socket
端口
使用SO_REUSEADDR選項時有兩點需要注意
public int getSoLinger() throws SocketException
public void setSoLinger(boolean on
這個Socket選項可以影響close方法的行為
如果底層的Socket實現不支持SO_LINGER都會拋出SocketException例外
if(socket
public int getSoTimeout() throws SocketException
public void setSoTimeout(int timeout) throws SocketException
這個Socket選項在前面已經討論過
如果將timeout設為
socket
當底層的Socket實現不支持SO_TIMEOUT選項時
public int getSendBufferSize() throws SocketException
public void setSendBufferSize(int size) throws SocketException
在默認情況下
如果底層的Socket實現不支持SO_SENDBUF選項
public int getReceiveBufferSize() throws SocketException
public void setReceiveBufferSize(int size) throws SocketException
在默認情況下
如果底層的Socket實現不支持SO_RCVBUF選項
public boolean getKeepAlive() throws SocketException
public void setKeepAlive(boolean on) throws SocketException
如果將這個Socket選項打開
socket
public boolean getOOBInline() throws SocketException
public void setOOBInline(boolean on) throws SocketException
如果這個Socket選項打開
public void sendUrgentData(int data) throws IOException
雖然sendUrgentData的參數data是int類型
package mynet;
import
import java
class Server
{
public static void main(String[] args) throws Exception
{
ServerSocket serverSocket = new ServerSocket(
System
while (true)
{
Socket socket = serverSocket
socket
InputStream in = socket
InputStreamReader inReader = new InputStreamReader(in);
BufferedReader bReader = new BufferedReader(inReader);
System
System
socket
}
}
}
public class Client
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket(
socket
OutputStream out = socket
OutputStreamWriter outWriter = new OutputStreamWriter(out);
outWriter
outWriter
socket
socket
outWriter
socket
socket
socket
socket
socket
}
}
由於運行上面的代碼需要一個服務器類
測試
由於本例使用了
運行Server
java mynet
運行Client
java mynet
在服務端控制台的輸出結果
服務器已經啟動
ABChello world
中國
在ClienT類中使用了sendUrgentData方法向服務器發送了字符
圖
從圖
在Client類中使用flush將緩沖區中的數據發送到服務器
在Client類中向服務器發送
注意
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26387.html