1 package org.xvsm.lookup.gnutella.threads;
2
3 import java.io.ObjectInputStream;
4 import java.io.ObjectOutputStream;
5 import java.net.InetAddress;
6 import java.net.InetSocketAddress;
7 import java.net.Socket;
8
9 import org.xvsm.lookup.gnutella.GnutellaPeer;
10 import org.xvsm.lookup.gnutella.objects.GnutellaAnswer;
11 import org.xvsm.lookup.gnutella.objects.GnutellaRequest;
12
13 /***
14 * Thread to send and receive requests to other peers after the connection has
15 * been established by the ListenerThread which then calls the ConnectionThread
16 * class to handle the connection.
17 *
18 * @author Hannu-Daniel Goiss
19 */
20 public class ConnectionThread extends Thread {
21 private GnutellaPeer peer;
22 private Socket socket;
23
24 public ConnectionThread(GnutellaPeer peer, Socket socket) {
25 this.peer = peer;
26 this.socket = socket;
27 }
28
29 public void run() {
30 try {
31 ObjectInputStream ois = new ObjectInputStream(socket
32 .getInputStream());
33
34 Object incoming = ois.readObject();
35
36 try {
37 GnutellaRequest request = (GnutellaRequest) incoming;
38
39 InetSocketAddress address = (InetSocketAddress) request
40 .getRequester();
41 if (!(address.getAddress().equals(InetAddress.getLocalHost()) == true && address
42 .getPort() == peer.getLocalPort())) {
43 if (peer.getList().containsKey(request.getSearchString()) == true) {
44 Socket answerSocket = new Socket();
45 answerSocket.connect(request.getRequester());
46
47 ObjectOutputStream oos = new ObjectOutputStream(
48 answerSocket.getOutputStream());
49 GnutellaAnswer answer = new GnutellaAnswer(request
50 .getSearchString(), peer.getList().get(
51 request.getSearchString()));
52
53 oos.writeObject(answer);
54 oos.flush();
55 oos.close();
56 } else {
57 if (request.getCounter() <= 2) {
58 request.incCounter();
59 peer.senden(request, false);
60 }
61 }
62 }
63
64 } catch (ClassCastException cce) {
65 GnutellaAnswer answer = (GnutellaAnswer) incoming;
66
67 peer.getAnswer().put(answer.getSearchString(),
68 answer.getObject());
69 }
70 ois.close();
71 socket.close();
72 } catch (Exception e) {
73 e.printStackTrace();
74 try {
75 socket.close();
76 } catch (Exception e2) {
77
78 }
79 }
80 }
81 }