糯米文學吧

位置:首頁 > 計算機 > java語言

Java如何通過Socket實現TCP服務端

java語言1.14W

Socket 通常也稱作“套接字”,Java如何通過Socket實現TCP服務端?下面本站小編帶大家一起來看看詳細內容,希望對大家有所幫助!想了解更多相關信息請持續關注我們應屆畢業生考試網!

Java如何通過Socket實現TCP服務端

  1 Java Socket簡介

所謂socket 通常也稱作”套接字“,用於描述IP地址和端口,是一個通信鏈的句柄。應用程序通常通過”套接字”向網絡發出請求或者應答網絡請求。Socket和ServerSocket類庫位於包中。ServerSocket用於服務器端,Socket是建立網絡連接時使用的。在連接成功時,應用程序兩端都會產生一個Socket實例,操作這個實例,完成所需的會話。對於一個網絡連接來説,套接字是平等的,並沒有差別,不因為在服務器端或在客户端而產生不同級別。

  2 TCPServer代碼實例

import ception;

import tStream;

import utStream;

import erSocket;

import et;

import ;

import Map;

import ;

import er;

import erFactory;

/**

* TCP服務器端,單例模式

* @author xiang

*

*/

public class TCPServer implements Runnable {

private static final Logger logger = ogger(s);

//成員變量/

private static TCPServer serverInstance;

private static Map<String, SocketThread> socketMaps = new HashMap<String,SocketThread>();        //每個客户端連接時都會新建一個SocketThread與之對應 private static ServerSocket serverSocket; //服務器套接字

private static int serPort = 9999; //服務器端口號

private static boolean flag; //服務器狀態標誌

private static final int BUFFER_SIZE = 512; //數據接收字符數組大小

//構造函數/

private TCPServer() {

}

/**

* 獲取實例

* @return TCPServer實例serverInstance

*/

public static TCPServer getServerInstance(){

if(serverInstance==null)

serverInstance = new TCPServer();

return serverInstance;

}

/**

* 開啟服務器

* @throws IOException

*/

public void openTCPServer() throws IOException{ if(serverSocket==null || osed()){

serverSocket = new ServerSocket(serPort);

flag = true;

}

}

/**

* 關閉服務器

* @throws IOException

*/

public void closeTCPServer() throws IOException{

flag = false; if(serverSocket!=null)

e();

/*for (y<String, SocketThread> entry : ySet()) {

tln("Key = " + ey() + ", Value = " + alue());

} */

for (SocketThread value : es())

eConnect();

r();

}

/**

* 服務器向客户端發送數據

* @param bytes[]:待發送的字符數組

* @param key 客户端的key,為空或""時表示數據羣發

* @throws IOException

*/

public void sendMessage(String key,byte[] msgBytes){

if(key==null||ls("")){

for (SocketThread value : es())

Massage(msgBytes);

}else{

SocketThread thread = (key);

if(thread!=null)

Massage(msgBytes);

}

}

/**

* 服務器向客户端發送數據

* @param key 客户端的`key,為空或""時表示數據羣發

* @param msgStr:待發送的字符串

* @throws IOException

*/

public void sendMessage(String key,String msgStr){ byte[] sendByte = ytes();

if(key==null||ls("")){

for (SocketThread value : es())

Massage(sendByte);

}else{

SocketThread thread = (key);

if(thread!=null)

Massage(sendByte);

}

}

@Override

public void run() {

("服務器線程已經啟動"); while(true){

try {

while(flag){

("服務器線程在監聽狀態中");

Socket socket = pt();

String key = emoteSocketAddress()ring();

SocketThread thread = new SocketThread(socket,key);

t();

(key, thread);

("有客户端連接:"+key);

}

} catch (Exception e) {

tStackTrace();

}

}

}

/**

* 處理連接後的數據接收請求內部類

* @author xiang

*

*/

private class SocketThread extends Thread{

private Socket socket;

private String key;

private OutputStream out;

private InputStream in;

//構造函數

public SocketThread(Socket socket,String key) {

et = socket;

= key;

}

/**

* 發送數據

* @param bytes

* @throws IOException

*/

public void sendMassage(byte[] bytes){

try {

if(out==null)

out = utputStream();

e(bytes);

} catch (Exception e) {

tStackTrace();

try {

closeConnect();

} catch (IOException e1) {

tStackTrace();

}

ve(key);

}

}

/**

* 關閉連接,釋放資源

* @throws IOException

*/

public void closeConnect() throws IOException{

if(out!=null) e();

if(in!=null) e();

if(socket!=null && nnected()) e();

}

@Override

public void run() {

byte[] receivBuf = new byte[BUFFER_SIZE];

int recvMsgSize;

try {

in = nputStream();

out = utputStream();

while ((recvMsgSize = (receivBuf)) != -1) {

String receivedData = new String(receivBuf, 0, recvMsgSize);

tln("Reverve form[port" + ort() + "]:" + receivedData);

tln("Now the size of socketMaps is" + ());

/**************************************************************

*

* 接收數據後的處理過程

*

**************************************************************/

}

// response to client

byte[] sendByte = "The Server has received"ytes();

// e(sendByte, 0, th);

e(sendByte);

tln("To Cliect[port:" + ort() + "] 回覆客户端的消息發送成功");

closeConnect();

ve(key);

} catch (Exception e) {

tStackTrace();

try {

closeConnect();

} catch (IOException e1) {

tStackTrace();

}

}

}

//////////////

public int getport(){

return ort();

}

}

//. end SocketThread

}