Не сте регистриран! Регистрирайте се БЕЗПЛАТНО, за да използвате услугите на сайта!

   Рубрики
 
 
 
 

 Форуми
» SEO и оптимизация
» Всичко за PHP и Perl
» Всичко за C, C++ и .NET
» Всичко за Java и JSP
» Всичко за SQL и MySQL
» Всичко за XHTML и CSS
» Презентация на сайтове
 Socket програмиране с Java - Пример: Разработка на forward сървър
  1. Въведение
  2. Примерен TCP forward сървър
  3. Как работи примерният TCP forward сървър
  4. TCP forward сървърът в действие
Magenta
     
Автор  Magenta (16.05.2004 17:35)  съобщение до автора
Погледнат  3211 пъти  добави към любими
Оценка  добави коментар
Гласове  5  изпрати на приятел
Коментари  (0)  абонирай се за Java
    Страница 2 / 4

 



CODE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
TCPForwardServer.java
import java.io.*;
import java.net.*;
 
/**
 *
TCPForwardServer is a simple TCP bridging software that
 *
allows a TCP port on some host to be transparently forwarded
 *
to some other TCP port on some other host. TCPForwardServer
 *
continuously accepts client connections on the listening TCP
 *
port (source port) and starts a thread (ClientThread) that
 *
connects to the destination host and starts forwarding the
 *
data between the client socket and destination socket.
 */
public class TCPForwardServer {
   
public static final int SOURCE_PORT = 2525;
   
public static final String DESTINATION_HOST = "mail.abv.bg";
   
public static final int DESTINATION_PORT = 25;
 
   
public static void main(String[] args) throws IOException {
       
ServerSocket serverSocket =
           
new ServerSocket(SOURCE_PORT);
       
while (true) {
           
Socket clientSocket = serverSocket.accept();
           
ClientThread clientThread =
               
new ClientThread(clientSocket);
           
clientThread.start();
       
}
    }
}

 
/**
 *
ClientThread is responsible for starting forwarding between
 *
the client and the server. It keeps track of the client and
 *
servers sockets that are both closed on input/output error
 *
durinf the forwarding. The forwarding is bidirectional and
 *
is performed by two ForwardThread instances.
 */
class ClientThread extends Thread {
   
private Socket mClientSocket;
   
private Socket mServerSocket;
   
private boolean mForwardingActive = false;
 
   
public ClientThread(Socket aClientSocket) {
       
mClientSocket = aClientSocket;
   
}
 
  
/**
     * Establishes connection to the destination server and
     * starts bidirectional forwarding ot data between the
     * client and the server.
     *
/
   
public void run() {
       
InputStream clientIn;
       
OutputStream clientOut;
       
InputStream serverIn;
       
OutputStream serverOut;
       
try {
          
// Connect to the destination server
            mServerSocket
= new Socket(
               
TCPForwardServer.DESTINATION_HOST,
               
TCPForwardServer.DESTINATION_PORT);
 
          
// Obtain client & server input & output streams
            clientIn
= mClientSocket.getInputStream();
           
clientOut = mClientSocket.getOutputStream();
           
serverIn = mServerSocket.getInputStream();
           
serverOut = mServerSocket.getOutputStream();
       
} catch (IOException ioe) {
           
System.err.println("Can not connect to " +
               
TCPForwardServer.DESTINATION_HOST + ":" +
               
TCPForwardServer.DESTINATION_PORT);
           
connectionBroken();
           
return;
       
}
 
      
// Start forwarding data between server and client
        mForwardingActive
= true;
       
ForwardThread clientForward =
           
new ForwardThread(this, clientIn, serverOut);
       
clientForward.start();
       
ForwardThread serverForward =
           
new ForwardThread(this, serverIn, clientOut);
       
serverForward.start();
 
       
System.out.println("TCP Forwarding " +
           
mClientSocket.getInetAddress().getHostAddress() +
           
":" + mClientSocket.getPort() + " <--> " +
           
mServerSocket.getInetAddress().getHostAddress() +
           
":" + mServerSocket.getPort() + " started.");
   
}
 
  
/**
     * Called by some of the forwarding threads to indicate
     * that its socket connection is brokean and both client
     * and server sockets should be closed. Closing the client
     * and server sockets causes all threads blocked on reading
     * or writing to these sockets to get an exception and to
     * finish their execution.
     *
/
   
public synchronized void connectionBroken() {
       
try {
           
mServerSocket.close();
       
} catch (Exception e) {}
       
try {
           
mClientSocket.close(); }
       
catch (Exception e) {}
 
 
       
if (mForwardingActive) {
           
System.out.println("TCP Forwarding " +
               
mClientSocket.getInetAddress().getHostAddress()
                +
":" + mClientSocket.getPort() + " <--> " +
               
mServerSocket.getInetAddress().getHostAddress()
                +
":" + mServerSocket.getPort() + " stopped.");
           
mForwardingActive = false;
       
}
    }
}

 
/**
 *
ForwardThread handles the TCP forwarding between a socket
 *
input stream (source) and a socket output stream (dest).
 *
It reads the input stream and forwards everything to the
 *
output stream. If some of the streams fails, the forwarding
 *
stops and the parent is notified to close all its sockets.
 */
class ForwardThread extends Thread {
   
private static final int BUFFER_SIZE = 8192;
 
   
InputStream mInputStream = null;
   
OutputStream mOutputStream = null;
   
ClientThread mParent = null;
 
  
/**
     * Creates a new traffic redirection thread specifying
     * its parent, input stream and output stream.
     *
/
   
public ForwardThread(ClientThread aParent, InputStream
            aInputStream
, OutputStream aOutputStream) {
       
mParent = aParent;
       
mInputStream = aInputStream;
       
mOutputStream = aOutputStream;
   
}
 
  
/**
     * Runs the thread. Continuously reads the input stream and
     * writes the read data to the output stream. If reading or
     * writing fail, exits the thread and notifies the parent
     * about the failure.
     *
/
   
public void run() {
       
byte[] buffer = new byte[BUFFER_SIZE];
       
try {
           
while (true) {
               
int bytesRead = mInputStream.read(buffer);
               
if (bytesRead == -1)
                   
break; // End of stream is reached --> exit
               
mOutputStream.write(buffer, 0, bytesRead);
               
mOutputStream.flush();
           
}
        }
catch (IOException e) {
          
// Read/write failed --> connection is broken
       
}
 
      
// Notify parent thread that the connection is broken
        mParent
.connectionBroken();
   
}
}



 << Предишна страница Следваща страница >> 


Ключови думи: Java socket програмиране forward сървър server


Още уроци от тази рубрика


 
  • Подобни теми от myLinks
 

 1 посетител чете този урок (0 потребители и 1 гост)  
Активни потребители: ---
   
  

Еmail  
 

 

 
  • Интересно от Софтуер
 



IT-PLACE.NET © 2004 - 2008