public void initializeServer(int port) { IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, port); serversocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); serversocket.Bind(endpoint); clientSockets = new Dictionary <IPEndPoint, Socket>(); Console.WriteLine("Server Initialized"); TCPCopyCatController.startListenOnSocketAsync(serversocket, ServerReceivedPacketCallback); }
public async Task <TCPCopyCatController.responseCode> connectToServer(IPEndPoint serverEndpoint) { const int connectionSequenceNumber = 0; if (socket == null) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } else if (socket.IsBound) { return(await getPacketResponse(connectionSequenceNumber + 1)); } TCPCopyCatController.startListenOnSocketAsync(socket, onPacketReceive); IPEndPoint test = new IPEndPoint(IPAddress.Any, 0); socket.Bind(test); this.serverEndpoint = serverEndpoint; TCPCopycatPacket.TCPCopycatHeader header = new TCPCopycatPacket.TCPCopycatHeader(); header.SYN = 1; header.sequenceNumber = connectionSequenceNumber; header.ACK = 0; header.dataLenght = 0; TCPCopycatPacket connectionPacket = new TCPCopycatPacket(header, new byte[1]); TCPCopycatReceiveMessageCallback receivedMessageCallbackLambda = delegate(TCPCopycatPacket packet, IPEndPoint sender) { if (packet.header.SYN == 1 && packet.header.acknowledgeNumber == (connectionSequenceNumber + 1)) { this.serverEndpoint = sender; return(TCPCopyCatController.responseCode.OK); } return(TCPCopyCatController.responseCode.UNKNOWN_ERROR); }; if (!TCPCopyCatController.sendMessageToEndPoint(socket, serverEndpoint, connectionPacket)) { registerPacket(connectionPacket, receivedMessageCallbackLambda, 1000); return(await getPacketResponse(connectionSequenceNumber + 1)); } else { return(TCPCopyCatController.responseCode.BAD_REQUEST); } }
public void ServerReceivedPacketCallback(TCPCopycatPacket packet, IPEndPoint sender) { Console.WriteLine("Received new connection from " + sender.Address + " port: " + sender.Port); clientSockets.Add(sender, new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)); IPEndPoint qwe = new IPEndPoint(IPAddress.Any, 0); clientSockets[sender].Bind(qwe); packetReceived.Add(GetClientSocketFromEndpoint(sender), new HashSet <int>()); filePacketList.Add(GetClientSocketFromEndpoint(sender), new List <TCPCopycatPacket>()); Console.WriteLine("Client socket listening on port: " + sender.Port.ToString()); TCPCopyCatController.startListenOnSocketAsync(GetClientSocketFromEndpoint(sender), ClientSocketReceivedPacketCallback); packet.header.acknowledgeNumber = packet.header.sequenceNumber + 1; TCPCopyCatController.sendMessageToEndPoint(GetClientSocketFromEndpoint(sender), sender, packet); }