자바,Socket 을 통 해 TCP 서버 구현
socket 이란 일반적으로'소켓'이 라 고도 부 르 는데 IP 주소 와 포트 를 설명 하 는 데 사용 되 며 통신 체인 의 핸들 입 니 다.응용 프로그램 은 보통'소켓'을 통 해 네트워크 에 요청 하거나 네트워크 요청 에 응답 합 니 다.Socket 과 ServerSocket 라 이브 러 리 는 자바.NET 패키지 에 있 습 니 다.서버 소켓 은 서버 쪽 에 사용 되 며,소켓 은 네트워크 연결 을 만 들 때 사용 된다.연결 이 성공 하면 프로그램 양쪽 에 Socket 인 스 턴 스 가 생 성 됩 니 다.이 인 스 턴 스 를 조작 하여 필요 한 세 션 을 완성 합 니 다.하나의 네트워크 연결 에 있어 서 소켓 은 평등 하고 차이 가 없 으 며 서버 쪽 이나 클 라 이언 트 에서 서로 다른 등급 이 발생 하지 않 습 니 다.
2 TCPServer 코드 인 스 턴 스
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TCP ,
* @author xiang
*
*/
public class TCPServer implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(TCPServer.class);
// /
private static TCPServer serverInstance;
private static Map socketMaps = new HashMap(); // 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 || serverSocket.isClosed()){
serverSocket = new ServerSocket(serPort);
flag = true;
}
}
/**
*
* @throws IOException
*/
public void closeTCPServer() throws IOException{
flag = false; if(serverSocket!=null)
serverSocket.close();
/*for (Map.Entry entry : socketMaps.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
} */
for (SocketThread value : socketMaps.values())
value.closeConnect();
socketMaps.clear();
}
/**
*
* @param bytes[]:
* @param key key, ""
* @throws IOException
*/
public void sendMessage(String key,byte[] msgBytes){
if(key==null||key.equals("")){
for (SocketThread value : socketMaps.values())
value.sendMassage(msgBytes);
}else{
SocketThread thread = socketMaps.get(key);
if(thread!=null)
thread.sendMassage(msgBytes);
}
}
/**
*
* @param key key, ""
* @param msgStr:
* @throws IOException
*/
public void sendMessage(String key,String msgStr){ byte[] sendByte = msgStr.getBytes();
if(key==null||key.equals("")){
for (SocketThread value : socketMaps.values())
value.sendMassage(sendByte);
}else{
SocketThread thread = socketMaps.get(key);
if(thread!=null)
thread.sendMassage(sendByte);
}
}
@Override
public void run() {
logger.info(" "); while(true){
try {
while(flag){
logger.info(" ");
Socket socket = serverSocket.accept();
String key = socket.getRemoteSocketAddress().toString();
SocketThread thread = new SocketThread(socket,key);
thread.start();
socketMaps.put(key, thread);
logger.info(" :"+key);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
*
* @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) {
this.socket = socket;
this.key = key;
}
/**
*
* @param bytes
* @throws IOException
*/
public void sendMassage(byte[] bytes){
try {
if(out==null)
out = socket.getOutputStream();
out.write(bytes);
} catch (Exception e) {
e.printStackTrace();
try {
closeConnect();
} catch (IOException e1) {
e1.printStackTrace();
}
socketMaps.remove(key);
}
}
/**
* ,
* @throws IOException
*/
public void closeConnect() throws IOException{
if(out!=null) out.close();
if(in!=null) in.close();
if(socket!=null && socket.isConnected()) socket.close();
}
@Override
public void run() {
byte[] receivBuf = new byte[BUFFER_SIZE];
int recvMsgSize;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
while ((recvMsgSize = in.read(receivBuf)) != -1) {
String receivedData = new String(receivBuf, 0, recvMsgSize);
System.out.println("Reverve form[port" + socket.getPort() + "]:" + receivedData);
System.out.println("Now the size of socketMaps is" + socketMaps.size());
/**************************************************************
*
*
*
**************************************************************/
}
// response to client
byte[] sendByte = "The Server has received".getBytes();
// out.write(sendByte, 0, sendByte.length);
out.write(sendByte);
System.out.println("To Cliect[port:" + socket.getPort() + "] ");
closeConnect();
socketMaps.remove(key);
} catch (Exception e) {
e.printStackTrace();
try {
closeConnect();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//////////////
public int getport(){
return socket.getPort();
}
}
//. end SocketThread
}
읽 어 주 셔 서 감사합니다. 여러분 에 게 도움 이 되 기 를 바 랍 니 다.본 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.