views:

133

answers:

1

greetings, i have the following code regarding asynchronous sockets programming:

    public void ServerBeginAceept(ushort ServerPort)
    {
        try
        {
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ServerPort);
            ServerSocket.Bind(ipEndPoint);
            ServerSocket.Listen(MAX_CONNECTIONS);
            IAsyncResult result = ServerSocket.BeginAccept(new AsyncCallback(ServerEndAccept), ServerSocket);
        }
    }


    public void ServerEndAccept(IAsyncResult iar)
    {
        try
        {
            ServerSocket = (Socket)iar.AsyncState;
            CommSocket = ServerSocket.EndAccept(iar);
        }
    }

    public void ClientBeginConnect(string ServerIP, ushort ServerPort)
    {
        try
        {
            CommSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ServerIP), ServerPort);
            IAsyncResult result = CommSocket.BeginConnect(ipEndPoint, new AsyncCallback(ClientEndConnect), CommSocket);

        }
    }


    public void ClientEndConnect(IAsyncResult iar)
    {
        try
        {
            CommSocket = (Socket)iar.AsyncState;
            CommSocket.EndConnect(iar);

            OnNetworkEvents eventArgs = new OnNetworkEvents(true, "Connected: " + CommSocket.RemoteEndPoint.ToString(), string.Empty);
            OnUpdateNetworkStatusMessage(this, eventArgs);
        }
    }

well there is nothing wrong with the code (i have simplified it and it is presented here as proof that im working on it an not looking for homework help!)

my Question is: how do i communicate with the server from a specified client port? the code here is all Server based port and this works well. but i would like to implement code that talks to a specific port on the client and not just one generated randomly by the server.

thank you for your time.

+3  A: 

Why do you want to use a specific port?

The client port is chosen randomly by design, because only one socket can have a port open at one time when it's not listening on that socket.

For example, if you always used port 80 on the client end of an HTTP connection, only one socket from that machine could connect to port 80 at a time. That would mean HTTP connections could not be parallel.

Moose
i did not know the manner in which sockets/port functions. this has been good education. thanks for your input.
iEisenhower