private synchronized Client allocateClient ( int targetPlayer , String description ) throws IOException { Client result = openClients . get ( targetPlayer ) ; if ( result == null ) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder . getInstance ( ) . getLatestAnnouncementFrom ( targetPlayer ) ; if ( deviceAnnouncement == null ) { throw new IllegalStateException ( "Player " + targetPlayer + " could not be found " + description ) ; } final int dbServerPort = getPlayerDBServerPort ( targetPlayer ) ; if ( dbServerPort < 0 ) { throw new IllegalStateException ( "Player " + targetPlayer + " does not have a db server " + description ) ; } final byte posingAsPlayerNumber = ( byte ) chooseAskingPlayerNumber ( targetPlayer ) ; Socket socket = null ; try { InetSocketAddress address = new InetSocketAddress ( deviceAnnouncement . getAddress ( ) , dbServerPort ) ; socket = new Socket ( ) ; socket . connect ( address , socketTimeout . get ( ) ) ; socket . setSoTimeout ( socketTimeout . get ( ) ) ; result = new Client ( socket , targetPlayer , posingAsPlayerNumber ) ; } catch ( IOException e ) { try { socket . close ( ) ; } catch ( IOException e2 ) { logger . error ( "Problem closing socket for failed client creation attempt " + description ) ; } throw e ; } openClients . put ( targetPlayer , result ) ; useCounts . put ( result , 0 ) ; } useCounts . put ( result , useCounts . get ( result ) + 1 ) ; return result ; }
Finds or opens a client to talk to the dbserver on the specified player incrementing its use count .