⑴ java Netty NIO 如何突破 65536 個埠的限制如何做到10萬~50萬的長連接
通常情況下衡陵是不可以突破的,埠有限制.單獨對外提供請求的服務不用考慮塵冊埠數量問題,監聽某一個埠即可.但咐兄戚是向提供代理伺服器,就不得不考慮埠數量受限問題了.當前的1M並發連接測試,也需要在客戶端突破6萬可用埠的限制.埠為16進制,那麼2的16次方值為65536,在linux系統裡面,1024以下埠都是超級管理員用戶(如root)才可以使用,普通用戶只能使用大於1024的埠值.
伺服器是只監聽一個埠,所有的客戶端連接,都是連接到伺服器的同一個埠上的。也就是說伺服器只是用了一個埠。就比如Http伺服器。默認只用了80埠。
nio 在linux上使用的是epoll ,epoll支持在一個進程中打開的FD是操作系統最大文件句柄數,而不是你所說的16位short表示的文件句柄。 而 select模型 單進程打開的FD是受限的 select模型默認FD是1024 。操作系統最大文件句柄數跟內存有關,1GB內存的機器上,大概是10萬個句柄左右。
⑵ http 怎麼實現長連接
通過輪詢來實現長連接
輪詢:隔一段時間訪問伺服器,伺服器不管有沒有新消息都立刻返回。
http長連接實現代碼:
客戶端:
package houlei.csdn.keepalive;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
/**
* C/S架構的客戶端對悔旦象,持有該對象,可以隨時向服務端發送消息。
*
* 創建時間:2011-7-18 上午12:17:25
* @author HouLei
* @since 1.0
*/
public class Client {
/**
* 處理服務端發回的對象,可實現該介面。
*/
public static interface ObjectAction{
void doAction(Object obj,Client client);
}
public static final class DefaultObjectAction implements ObjectAction{
public void doAction(Object obj,Client client) {
System.out.println("處理謹敗:\t"+obj.toString());//診斷程序是否正常祥前顫
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
String serverIp = "127.0.0.1";
int port = 65432;
Client client = new Client(serverIp,port);
client.start();
}
private String serverIp;
private int port;
private Socket socket;
private boolean running=false;
private long lastSendTime;
private ConcurrentHashMap actionMapping = new ConcurrentHashMap();
public Client(String serverIp, int port) {
this.serverIp=serverIp;this.port=port;
}
public void start() throws UnknownHostException, IOException {
if(running)return;
socket = new Socket(serverIp,port);
System.out.println("本地埠:"+socket.getLocalPort());
lastSendTime=System.currentTimeMillis();
running=true;
new Thread(new KeepAliveWatchDog()).start();
new Thread(new ReceiveWatchDog()).start();
}
public void stop(){
if(running)running=false;
}
/**
* 添加接收對象的處理對象。
* @param cls 待處理的對象,其所屬的類。
* @param action 處理過程對象。
*/
public void addActionMap(Class cls,ObjectAction action){
actionMapping.put(cls, action);
}
public void sendObject(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(obj);
System.out.println("發送:\t"+obj);
oos.flush();
}
class KeepAliveWatchDog implements Runnable{
long checkDelay = 10;
long keepAliveDelay = 2000;
public void run() {
while(running){
if(System.currentTimeMillis()-lastSendTime>keepAliveDelay){
try {
Client.this.sendObject(new KeepAlive());
} catch (IOException e) {
e.printStackTrace();
Client.this.stop();
}
lastSendTime = System.currentTimeMillis();
}else{
try {
Thread.sleep(checkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
class ReceiveWatchDog implements Runnable{
public void run() {
while(running){
try {
InputStream in = socket.getInputStream();
if(in.available()>0){
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
System.out.println("接收:\t"+obj);//接受數據
ObjectAction oa = actionMapping.get(obj.getClass());
oa = oa==null?new DefaultObjectAction():oa;
oa.doAction(obj, Client.this);
}else{
Thread.sleep(10);
}
} catch (Exception e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
服務端:
package houlei.csdn.keepalive;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
/**
* C/S架構的服務端對象。
*
* 創建時間:2011-7-18 上午12:17:37
* @author HouLei
* @since 1.0
*/
public class Server {
/**
* 要處理客戶端發來的對象,並返回一個對象,可實現該介面。
*/
public interface ObjectAction{
Object doAction(Object rev);
}
public static final class DefaultObjectAction implements ObjectAction{
public Object doAction(Object rev) {
System.out.println("處理並返回:"+rev);//確認長連接狀況
return rev;
}
}
public static void main(String[] args) {
int port = 65432;
Server server = new Server(port);
server.start();
}
private int port;
private volatile boolean running=false;
private long receiveTimeDelay=3000;
private ConcurrentHashMap actionMapping = new ConcurrentHashMap();
private Thread connWatchDog;
public Server(int port) {
this.port = port;
}
public void start(){
if(running)return;
running=true;
connWatchDog = new Thread(new ConnWatchDog());
connWatchDog.start();
}
@SuppressWarnings("deprecation")
public void stop(){
if(running)running=false;
if(connWatchDog!=null)connWatchDog.stop();
}
public void addActionMap(Class cls,ObjectAction action){
actionMapping.put(cls, action);
}
class ConnWatchDog implements Runnable{
public void run(){
try {
ServerSocket ss = new ServerSocket(port,5);
while(running){
Socket s = ss.accept();
new Thread(new SocketAction(s)).start();
}
} catch (IOException e) {
e.printStackTrace();
Server.this.stop();
}
}
}
class SocketAction implements Runnable{
Socket s;
boolean run=true;
long lastReceiveTime = System.currentTimeMillis();
public SocketAction(Socket s) {
this.s = s;
}
public void run() {
while(running && run){
if(System.currentTimeMillis()-lastReceiveTime>receiveTimeDelay){
overThis();
}else{
try {
InputStream in = s.getInputStream();
if(in.available()>0){
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
lastReceiveTime = System.currentTimeMillis();
System.out.println("接收:\t"+obj);
ObjectAction oa = actionMapping.get(obj.getClass());
oa = oa==null?new DefaultObjectAction():oa;
Object out = oa.doAction(obj);
if(out!=null){
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(out);
oos.flush();
}
}else{
Thread.sleep(10);
}
} catch (Exception e) {
e.printStackTrace();
overThis();
}
}
}
}
private void overThis() {
if(run)run=false;
if(s!=null){
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("關閉:"+s.getRemoteSocketAddress());//關閉長連接
}
}
}
長連接的維持,是要客戶端程序,定時向服務端程序,發送一個維持連接包的。
如果,長時間未發送維持連接包,服務端程序將斷開連接。
⑶ 如何實現一個伺服器與多個客戶端連接
TCP協議:
伺服器端:tcp_server.c
[cpp] view plainprint?
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd;//伺服器端套接字
int client_sockfd;//客戶端套接字
int len;
struct sockaddr_in my_addr; //伺服器網路地址結構體
struct sockaddr_in remote_addr; //客戶端網路地址結構體
int sin_size;
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&my_addr,0,sizeof(my_addr)); //數據初始化--清零
my_addr.sin_family=AF_INET; //設置為IP通信
my_addr.sin_addr.s_addr=INADDR_ANY;//伺服器IP地址--允許連接到所有本地地址上
my_addr.sin_port=htons(8000); //伺服器埠號
/*創建伺服器端套接字--IPv4協議,面向連接通信,TCP協議*/
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
/*監聽連接請求--監聽隊列長度為5*/
listen(server_sockfd,5);
sin_size=sizeof(struct sockaddr_in);
/*等待客戶端連接請求到達*/
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
return 1;
}
printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr));
len=send(client_sockfd,"Welcome to my server/n",21,0);//發送歡迎信息
/*接收客戶端的數據並將其發送給客戶端--recv返回接收到的位元組數,send返回發送的位元組數*/
while((len=recv(client_sockfd,buf,BUFSIZ,0))>0))
{
buf[len]='/0';
printf("%s/n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write");
return 1;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd;//伺服器端套接字
int client_sockfd;//客戶端套接字
int len;
struct sockaddr_in my_addr; //伺服器網路地址結構體
struct sockaddr_in remote_addr; //客戶端網路地址結構體
int sin_size;
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&my_addr,0,sizeof(my_addr)); //數據初始化--清零
my_addr.sin_family=AF_INET; //設置為IP通信
my_addr.sin_addr.s_addr=INADDR_ANY;//伺服器IP地址--允許連接到所有本地地址上
my_addr.sin_port=htons(8000); //伺服器埠號
/*創建伺服器端套接字--IPv4協議,面向連接通信,TCP協議*/
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
/*監聽連接請求--監聽隊列長度為5*/
listen(server_sockfd,5);
sin_size=sizeof(struct sockaddr_in);
/*等待客戶端連接請求到達*/
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
return 1;
}
printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr));
len=send(client_sockfd,"Welcome to my server/n",21,0);//發送歡迎信息
/*接收客戶端的數據並將其發送給客戶端--recv返回接收到的位元組數,send返回發送的位元組數*/
while((len=recv(client_sockfd,buf,BUFSIZ,0))>0))
{
buf[len]='/0';
printf("%s/n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write");
return 1;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}
TCP協議:
客戶端:tcp_client.c
[c-sharp] view plainprint?
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int client_sockfd;
int len;
struct sockaddr_in remote_addr; //伺服器端網路地址結構體
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&remote_addr,0,sizeof(remote_addr)); //數據初始化--清零
remote_addr.sin_family=AF_INET; //設置為IP通信
remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");//伺服器IP地址
remote_addr.sin_port=htons(8000); //伺服器埠號
/*創建客戶端套接字--IPv4協議,面向連接通信,TCP協議*/
if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)
{
perror("connect");
return 1;
}
printf("connected to server/n");
len=recv(client_sockfd,buf,BUFSIZ,0);//接收伺服器端信息
buf[len]='/0';
printf("%s",buf); //列印伺服器端信息
/*循環的發送接收信息並列印接收信息--recv返回接收到的位元組數,send返回發送的位元組數*/
while(1)
{
printf("Enter string to send:");
scanf("%s",buf);
if(!strcmp(buf,"quit")
break;
len=send(client_sockfd,buf,strlen(buf),0);
len=recv(client_sockfd,buf,BUFSIZ,0);
buf[len]='/0';
printf("received:%s/n",buf);
}
close(client_sockfd);//關閉套接字
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int client_sockfd;
int len;
struct sockaddr_in remote_addr; //伺服器端網路地址結構體
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&remote_addr,0,sizeof(remote_addr)); //數據初始化--清零
remote_addr.sin_family=AF_INET; //設置為IP通信
remote_addr.sin_addr.s_addr=inet_addr("127.0.0.1");//伺服器IP地址
remote_addr.sin_port=htons(8000); //伺服器埠號
/*創建客戶端套接字--IPv4協議,面向連接通信,TCP協議*/
if((client_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if(connect(client_sockfd,(struct sockaddr *)&remote_addr,sizeof(struct sockaddr))<0)
{
perror("connect");
return 1;
}
printf("connected to server/n");
len=recv(client_sockfd,buf,BUFSIZ,0);//接收伺服器端信息
buf[len]='/0';
printf("%s",buf); //列印伺服器端信息
/*循環的發送接收信息並列印接收信息--recv返回接收到的位元組數,send返回發送的位元組數*/
while(1)
{
printf("Enter string to send:");
scanf("%s",buf);
if(!strcmp(buf,"quit")
break;
len=send(client_sockfd,buf,strlen(buf),0);
len=recv(client_sockfd,buf,BUFSIZ,0);
buf[len]='/0';
printf("received:%s/n",buf);
}
close(client_sockfd);//關閉套接字
return 0;
}
UDP協議:
伺服器端:udp_server.c
[cpp] view plainprint?
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd;
int len;
struct sockaddr_in my_addr; //伺服器網路地址結構體
struct sockaddr_in remote_addr; //客戶端網路地址結構體
int sin_size;
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&my_addr,0,sizeof(my_addr)); //數據初始化--清零
my_addr.sin_family=AF_INET; //設置為IP通信
my_addr.sin_addr.s_addr=INADDR_ANY;//伺服器IP地址--允許連接到所有本地地址上
my_addr.sin_port=htons(8000); //伺服器埠號
/*創建伺服器端套接字--IPv4協議,面向無連接通信,UDP協議*/
if((server_sockfd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
sin_size=sizeof(struct sockaddr_in);
printf("waiting for a packet.../n");
/*接收客戶端的數據並將其發送給客戶端--recvfrom是無連接的*/
if((len=recvfrom(server_sockfd,buf,BUFSIZ,0,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("recvfrom");
return 1;
}
printf("received packet from %s:/n",inet_ntoa(remote_addr.sin_addr));
buf[len]='/0';
printf("contents: %s/n",buf);
close(server_sockfd);
return 0;
}
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd;
int len;
struct sockaddr_in my_addr; //伺服器網路地址結構體
struct sockaddr_in remote_addr; //客戶端網路地址結構體
int sin_size;
char buf[BUFSIZ]; //數據傳送的緩沖區
memset(&my_addr,0,sizeof(my_addr)); //數據初始化--清零
my_addr.sin_family=AF_INET; //設置為IP通信
my_addr.sin_addr.s_addr=INADDR_ANY;//伺服器IP地址--允許連接到所有本地地址上
my_addr.sin_port=htons(8000); //伺服器埠號
/*創建伺服器端套接字--IPv4協議,面向無連接通信,UDP協議*/
if((server_sockfd=socket(PF_INET,SOCK_DGRAM,0))<0)
{
perror("socket");
return 1;
}
/*將套接字綁定到伺服器的網路地址上*/
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
sin_size=sizeof(struct sockaddr_in);
printf("waiting for a packet.../n");
/*接收客戶端的數據並將其發送給客戶端--recvfrom是無連接的*/
if((len=recvfrom(server_sockfd,buf,BUFSIZ,0,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("recvfrom");
return 1;
}
printf("received packet from %s:/n",inet_ntoa(remote_addr.sin_addr));
buf[len]='/0';
printf("contents: %s/n",buf);
close(server_sockfd);
return 0;
}
⑷ 一個TCP埠怎麼同時連接多個伺服器
一個埠可以同時進行多個聯接,這裡面有多個模型可供選擇,最好的模型IOCP模型。你還是應該找些書來看一下。