Java Client-Server Socket can only send 1 file [duplicate] - java

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I am doing a sample client-server socket project where the server sends a file to the client and the client saves it in a destination folder. It works well BUT it only works ONCE. I have to restart the server and reconnect the client in order to send another file.
What am I doing wrong?
Server:
public void doConnect() {
try {
InetAddress addr = InetAddress.getByName(currentIPaddress);
serverSocket = new ServerSocket(4445, 50, addr);
isServerStarted = true;
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
String command = inputStream.readUTF();
this.statusBox.setText("Received message from Client: " + command);
} catch (IOException e) {
e.printStackTrace();
}
}
Method that I use to send the file from server
public void sendFile() {
fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
//Now writing the FileEvent object to socket
try {
outputStream.writeUTF("newfile");
outputStream.flush();
outputStream.writeObject(fileEvent);
String result = inputStream.readUTF();
System.out.println("client says: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
Client
public void connect() {
int retryCount = 0;
while (!isConnected) {
if (retryCount < 5) {
try {
socket = new Socket(currentIPAddress, currentPort);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
isConnected = true;
//connection success
String command = inputStream.readUTF();
if (command.equals("newfile")) {
this.clientCmdStatus.setText("Received a file from Server");
outputStream.writeUTF("Thanks Server! Client Received the file");
outputStream.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
new Thread(new DownloadingThread()).start();
}
} catch (IOException e) {
e.printStackTrace();
retryCount++;
}
} else {
//Timed out. Make sure Server is running & Retry
retryCount = 0;
break;
}
}
}
Code used for downloading file in client
public void downloadFile() {
try {
fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = destinationPath + fileEvent.getFilename();
if (!new File(destinationPath).exists()) {
new File(destinationPath).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
serverResponsesBox.setText("File received from server: " + fileEvent.getFilename());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

In order to get the server accept another (and more) connections, you have to put it into a loop
while(someConditionIndicatingYourServerShouldRun) {
Socker socket = serverSocket.accept();
//respond to the client
}
I'd recommend using a thread pool and submit the processing to the thread pool, i.e. by using an ExecutorService. Further, you should close Resources such as stream when finished, the "try-with-resources" construct helps you with that. So your code might look like this
ServerSocket serverSocket = ...;
ExecutorService threadPool = Executors.newFixedThreadPool(10);
AtomicBoolean running = new AtomicBoolean(true);
while(running.get()) {
Socket socket = serverSocket.accept();
threadPool.submit(() -> {
try(ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
OutputStream os = new ObjectOutputStream(socket.getOutputStream())) {
String command = is.readUTF();
if("shutdown".equals(command)) {
running.set(false);
} else {
this.statusBox.setText("Received message from Client: " + command);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}

Related

Java how to read with ObjectInputStream

It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}

Sending multiple data over socket

I made a multiplayer snake game which is sending the actual score and health to the opponent over socket. The problem is during the game, the enemies health will be its score.
Example the enemy has 90 health and 15 score. When the enemy get 1 score it health will be 16 and the score remains 15. I think the problem is somewhere in the server:
private boolean listenForServerRequest() {
Socket socket = null;
try {
socket = serverSocket.accept();
dos = new DataOutputStream(socket.getOutputStream());
dos2 = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dis2 = new DataInputStream(socket.getInputStream());
accepted = true;
System.out.println("Client has requested and joined the game");
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean connect() {
try {
socket = new Socket(ip, port);
dos = new DataOutputStream(socket.getOutputStream());
dos2 = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dis2 = new DataInputStream(socket.getInputStream());
accepted = true;
} catch (IOException e) {
System.out.println("Unable to connect to the address: " + ip + ":" + port + " | Starting a server");
return false;
}
System.out.println("Successfully connected to the server.");
return true;
}
private void initializeServer() {
try {
serverSocket = new ServerSocket(port, 8, InetAddress.getByName(ip));
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean getConnected() {
return this.connected;
}
public void sendHealth(SnakeHead snakeHead) {
try {
dos.writeInt(snakeHead.getHealth());
System.out.println(snakeHead.getHealth());
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendScore(SnakeHead snakeHead) {
try {
dos2.writeInt(Globals.getScore());
System.out.println(snakeHead.getHealth());
dos2.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getEnemyHealth() {
try{if (dis.available() != 0 ) {
try {
enemyHealth = dis.readInt();
return enemyHealth;
} catch (IOException e) {
e.printStackTrace();
}
}}catch (IOException e){
e.printStackTrace();
}
return enemyHealth;
}
public int getEnemyScore() {
try{if (dis2.available() != 0) {
try {
enemyScore = dis2.readInt();
return enemyScore;
} catch (IOException e) {
e.printStackTrace();
}
}}catch (IOException e){
e.printStackTrace();
}
return enemyScore;
}
Hope someone will find the problem or has any advice! Thanks!
Sending multiple data is not a problem. Socket works in TCP mode in this example so write order = read order. To avoid serialization, I would suggest you to send separated values in form of String and use PrintWriter for this purpose. This would send data in "one shot"
See this example:
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
// reading
String userInput;
while ((userInput = stdIn.readLine()) != null) {
System.out.println("echo: " + in.readLine());
}
// writing
out.println(int + "," + int); // multiple data
)
With socket.getOutputStream() you will get the same stream each time
You have to send the data in a struct , containing the score and health, or you have to send them separately in sequence (like first the health then the score or vicevesa)

Java socket can client can not read the data

The client send a message, then the server receives the message and response the message. I don't know why the client can not read the response. If I remove the read part in client, the server can get the message. However for the following code, nothing work. Also I tried the flush(), it still doesn't work.
For client
public void run() {
try (Socket echoSocket = new Socket(HOSTNAME, Integer.parseInt(PORTNUMBER));
DataOutputStream dOut = new DataOutputStream(echoSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(echoSocket.getInputStream());
) {
while (true) {
command = UI.commandQueue.take()
dOut.writeInt(Message.toByteArray(command).length);
dOut.write(Message.toByteArray(command));
int length;
while((length = dIn.readInt()) != 0) {
if (length > 0){
byte[] messagebyte = new byte[length];
dIn.readFully(messagebyte, 0, messagebyte.length);
try {
msg = Message.fromByteArray(messagebyte);
testDisplay(msg);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
testDisplay(msg);
}
}
}
}catch (UnknownHostException e) {
UI.display("Don't know about host " + HOSTNAME);
} catch (IOException e) {
UI.display("Couldn't get I/O for the connection to " + HOSTNAME);
}
}
For server
public void run() {
try (ServerSocket serverSocket = new ServerSocket(Integer.parseInt(PORT_NUMBER));
Socket clientSocket = serverSocket.accept();
DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());) {
int length;
while ((length = dIn.readInt()) != 0) {
if (length > 0) {
byte[] messagebyte = new byte[length];
dIn.readFully(messagebyte, 0, messagebyte.length); // read the
// message
Message msg;
try {
msg = Message.fromByteArray(messagebyte);
testDisplay(msg);
dOut.writeInt(Message.toByteArray(msg).length);
dOut.write(Message.toByteArray(msg));
UI.display("ack sent");
} catch (Exception e) {
// TODO Auto-generated catch block
UI.display(e.getMessage());
}
}
}
} catch (IOException e) {
UI.display(
"Exception caught when trying to listen on port " + PORT_NUMBER + " or listening for a connection");
UI.display(e.getMessage());
}
}
Your server is echoing one response per request, but your client is trying to read more than one response per request, which it will never get, so it blocks.

how can i transfer multiple files in a directory from client to server through java socket? [duplicate]

This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I have created a simple client-server java socket app that can transfer a single file from client into the server through socket. What do I need to modify in my application so that I can send multiple files in a directory to the server?
this my simple client:
public void connect() {
while (!isConnected) {
try {
socket = new Socket("10.110.190.82", 7999);
outputStream = new ObjectOutputStream(socket.getOutputStream());
isConnected = true;
} catch (IOException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error. Server is not running\n '"+e.getMessage()+"' "+
"\nThis Client will now close.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
public void sendFile(String sourceFilePath, String fileName) {
if(socket.isConnected()){
while (socket.isConnected()) {
fileEvent = new FileEvent_1();
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read,
fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
try {
outputStream.writeObject(fileEvent);
System.out.println("Done...Going to exit");
JOptionPane.showMessageDialog(null, "Upload Success", "Success", JOptionPane.INFORMATION_MESSAGE);
Thread.sleep(3000);
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
} catch(InterruptedException ex){
ex.printStackTrace();
}
}
} else {
JOptionPane.showMessageDialog(null, "Socket is not connected", "FAILED", JOptionPane.ERROR_MESSAGE);
}
}
and this is my simple server, it contains a client handler and a server..
this is client_handler:
public class ClientHandler implements Runnable {
Socket socket;
PrintStream out;
private ObjectInputStream inputStream;
private FileEvent_1 fileEvent;
private File dstFile;
private FileOutputStream fileOutputStream;
ClientHandler(Socket s) {
socket = s;
}
#Override
public void run() {
try {
out = new PrintStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
downloadFile();
} catch (IOException e) {
System.out.println("PrintStream Error");
}
out.println("Hello!! I'm in!!!");
try {
socket.close();
} catch (IOException e) {
System.out.println("Failed to close, oddly...");
}
}
public void downloadFile() {
try {
fileEvent = (FileEvent_1) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = fileEvent.getDestinationDirectory() + fileEvent.getFilename();
if (!new File(fileEvent.getDestinationDirectory()).exists()) {
new File(fileEvent.getDestinationDirectory()).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
Thread.sleep(000);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}}
and the server:
public static void main(String[] args) {
try {
socket = new ServerSocket(port);
System.out.println("SERVER START");
System.out.println("Bound to port: " + port);
} catch (IOException e) {
System.out.println("Cannot bind to port: " + port);
System.exit(0);
}
while (true) {
try {
Socket s = socket.accept();
System.out.println("New Client: "+s.getInetAddress().toString());
(new Thread(new ClientHandler(s))).start();
} catch (IOException e) {
System.out.println("Failed to accept client");
}
}
}
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
So you get the directory listing (list of all files in the directory), loop through the resulting fList and send them one by one as you would with a single file:
for(File file : fList) {
//file sending stuff
}
You can use JFileChooser if you want see the list of directories and list of files. for example:
JFileChooser jFilechooser1= new JFileChooser(new File("."));
to select the file:
if (jFilechooser1.showOpenDialog(this)==JFileChooser.APPROVE_OPTION)
{
dstFile=jFilechooser1.getSelectedFile();
}

rtsp client code not working

I am facing problem in Java socket communication, I am running Live555 Media Server and one small app (some what similar to proxy server code, referred one online code snippet) in one machine, and also created one client code and running in my laptop. All machines are in same network. When I send RTSP Command from client to proxy, It is receiving properly and it is redirecting that received command to Live555 server and its getting back proper response but the response is not receiving in client. Help me to fix this problem and also suggest me some doc link to understand the problem.
here is my proxy code,
public class TestProxyServer {
public static void main(String[] args) {
try {
String host = "127.0.0.1";
int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting proxy for " + host + ":" + serverPort
+ " on port " + proxyPort);
runServer(host, serverPort, proxyPort);
} catch(Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sProt, int pPort) throws IOException {
ServerSocket ss = new ServerSocket(pPort);
final byte[] request = new byte[1024];
byte[] replay = new byte[1024];
while(true) {
Socket server = null, client = null;
try {
client = ss.accept();
final InputStream fromClient = client.getInputStream();
final OutputStream toClient = client.getOutputStream();
// for Live555
try {
server = new Socket(host, sProt);
} catch(Exception e) {
PrintWriter out = new PrintWriter(toClient);
out.print("Proxy can not connect to Live555 on host " + host + " with the port " + sProt + "\n");
out.flush();
client.close();
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String ClientMSG;
while((bytesRead = fromClient.read(request)) != -1) {
toServer.write(request, 0, bytesRead);
ClientMSG = new String(request, 0, bytesRead);
System.err.println("From Client : " + ClientMSG);
toServer.flush();
}
} catch(Exception e) {
try {toServer.close();} catch(IOException ioe){}
}
}
};
t.start();
int bytesRead;
try {
String toCMSG;
while((bytesRead = fromServer.read(replay)) != -1) {
toClient.write(replay, 0, bytesRead);
toCMSG = new String(replay, 0, bytesRead);
System.err.println("Response from Live555 " + toCMSG);
toClient.flush();
}
} catch(Exception e) {
toClient.close();
// e.printStackTrace();
}
} catch(Exception e) {
e.printStackTrace();
} finally {
if(server != null)
server.close();
if(client != null)
client.close();
}
}
}
}
and client code is here,
public class Test {
public static void main(String[] args) {
try {
String host = "192.168.1.9";
// int serverPort = 8554;
int proxyPort = 5555;
System.out.println("Starting Client to connect proxy on " + host + ":" + " with port " + proxyPort);
runServer(host, proxyPort);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void runServer(String host, int sPort) throws IOException {
final byte[] request = new byte[1024];
final byte[] reply = new byte[1024];
while (true) {
Socket server = null;
try {
// for Proxy
try {
server = new Socket(host, sPort);
} catch (Exception e) {
System.out.println("Proxy can not connect to ProxyServer on host " + host + " with the port " + sPort + "\n");
continue;
}
final InputStream fromServer = server.getInputStream();
final OutputStream toServer = server.getOutputStream();
int bytesRead;
try {
String RtspMSG = "DESCRIBE rtsp://192.168.1.9:8554/free.ts RTSP/1.0\r\nCSeq: 2\r\n\r\n";
// while((bytesRead = fromClient.read(RtspMSG.getBytes()))
// != -1) {
toServer.write(RtspMSG.getBytes(), 0, RtspMSG.length());
System.err.println("Sent : " + RtspMSG);
toServer.flush();
// }
} catch (Exception e) {
try {
toServer.close();
} catch (IOException ioe) {
}
}
Thread t = new Thread() {
public void run() {
int bytesRead;
try {
String response = null;
System.err.println("----------------------------------");
while ((bytesRead = fromServer.read(reply)) != -1) {
response = new String(reply, 0, bytesRead);
}
System.err.println("Response from Proxy : "
+ response);
} catch (Exception e) {
try {
fromServer.close();
} catch (Exception e1) {
}
// e.printStackTrace();
}
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (server != null)
server.close();
}
}
}
}
Thank You

Categories

Resources