服务器是如何监听端口发过来的数据

服务器是如何监听端口发过来的数据,第1张

在收到消息的函数里面,会有一个参数,如果是用Windows API做的话,就有一个sockaddr_in的结构体,里面包含了对方的IP和端口,记得端口是高低字节错位的,把高8位和低8位调换一下就好了。

有了对方的IP和端口,直接再向这个IP和端口发消息就好了。

可以考虑用JAVA实现监听客户端口,参考例子如下:

package test; 

import javaioByteArrayOutputStream;

import javaioIOException;

import javaioInputStream;

import javaioOutputStream;

import javalangreflectMethod;

import javanetDatagramPacket;

import javanetDatagramSocket;

import javanetInetAddress;

import javanetServerSocket;

import javanetSocket;

import javanetSocketException;

import javautilHashMap;

import javautilLinkedList;

import javautilList;

import javautilRandom;

/

  该程序用的DatagramSocket,实现UDP的通讯

  @author D'Addario

 

 /

public class Test{

 

    private int headLen = 12;//消息起点和终点的记录 例如classAclassB就是发往classA的消息,发送者是classB

    private Random random;

    private String serverIp;

    private int serverPort;

    private  HashMap<String,Classes> map ;

    {

        serverIp = "127001";

        serverPort = 9999; 

        random = new Random(SystemcurrentTimeMillis());

        map = new HashMap<String,Classes>();

        Classes A = Testthisnew Classes();

        Aip = "127001";

        Aname = "我是A";

        Aport = 10000;

        mapput("classA", A);

 

        Classes B = Testthisnew Classes();

        Bip = "127001";

        Bname = "我是B";

        Bport = 10001;

        mapput("classB", B);

    }

    public static void main(String[] a) throws  Exception{

        Test test = new Test();

        new Thread(testnew Server())start();

        Client client1 = testnew Client();

        client1mine = "classA";

        client1remote = "classB";

        new Thread(client1)start();

 

        Client client2 = testnew Client();

        client2mine = "classB";

        client2remote = "classA";

        new Thread(client2)start();

 

    }

    /

      成员 用于记录 每个成员的个性信息

      @author D'Addario

     

     /

    private class Classes {

        private String name ; //成员姓名

        private String ip ; //成员ip

        private int port;//成员的client server 监听端口

    }

    /

      server 用于转发两个client之间消息的类

      @author D'Addario

     

     /

    private class Server implements Runnable{

 

        public void run() {

            // TODO Auto-generated method stub

            boolean start = false;

            DatagramSocket socket = null;

            try {

                socket = new DatagramSocket(serverPort);

                start = true;

            } catch (SocketException e1) {

 

                e1printStackTrace();

            }

            while(start)

            {

 

                try {

 

                    byte[] data = new byte[1024];

                    DatagramPacket packet = new DatagramPacket(data,datalength);

                    socketreceive(packet);

                    int len = packetgetLength();

                    //Systemoutprintln("recevie data:"+new String(data,0,len));                

                    if(len<headLen)

                        throw new IOException("无效数据");

                    String id = new String(data,0,headLen/2);//获取发往对象的ID

                    String id2 = new String(data,headLen/2,headLen/2);    

                    Systemoutprintln("receive from "+id2 +", send to "+id+",msg["+new String(data,headLen,len-headLen)+"]");

                    Classes one = mapget(idtrim());        

                    DatagramPacket retPack = new DatagramPacket(data,0,len,InetAddressgetByName(oneip),oneport);

                    socketsend(retPack);

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    eprintStackTrace();

                }

            }

        }

    }

    /

      Client 客户端类,用于客户端消息的发送

      @author D'Addario

     

     /

    private class Client implements Runnable{

 

        private String mine;

        private String remote;

 

 

        public void run() {

            // TODO Auto-generated method stub

            String msg = remote+mine;

            DatagramSocket socket = null;

            try {

                socket = new DatagramSocket(mapget(mine)port);

                ClientServer srv=new ClientServer();

                srvsetSocket(socket);

                new Thread(srv)start();

            } catch (SocketException e) {

                // TODO Auto-generated catch block

                eprintStackTrace();

            }

            byte[] data ;

            while(true)

            {

                String sendStr = msg + "给我"+randomnextInt(5000)+"分吧";

                data = sendStrgetBytes();

 

                try {

                    DatagramPacket retPack = new DatagramPacket(data,0,datalength,InetAddressgetByName(serverIp),serverPort);

                    socketsend(retPack);

                    Threadsleep(randomnextInt(5)1000);

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    eprintStackTrace();

                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    eprintStackTrace();

                }

 

 

            }

        }    

    }

    /

      客户端server 用于监听服务器的消息

      @author D'Addario

     

     /

    private class ClientServer implements Runnable{

        DatagramSocket socket ;

 

        public DatagramSocket getSocket() {

            return socket;

        }

 

        public void setSocket(DatagramSocket socket) {

            thissocket = socket;

        }

 

        public void run() {

            byte[] data = new byte[1024];

            DatagramPacket packet = new DatagramPacket(data,datalength);

            while(true){

                try {

                    socketreceive(packet);

                    int len = packetgetLength();

                    if(len<headLen)

                        throw new IOException("无效数据");

                    Systemoutprintln("I get the message :"+ThreadcurrentThread()getId()+"-->["+new String(data,0,len)+"]");

                } catch (IOException e) {

                    // TODO Auto-generated catch block

                    eprintStackTrace();

                }    }        

        }

 

    }

 

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 服务器是如何监听端口发过来的数据

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情