how to reuse TCP Socket connection(possible setReuseAddress(true), but not work for me) for download multiple files from Server(Apache, HTTPD) in on connection without disconnect(and connect again).
My code below..
public class ClientThread implements Runnable {
public void run() {
try {
Log.d("ClientActivity", "C: Connecting...");
SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
socket = new Socket();
socket.setReuseAddress(true);
socket.setKeepAlive(true);
socket.setSoLinger(true, 3000);
socket.connect(sockaddr);
if (socket.isConnected()) {
DataInputStream input = new DataInputStream(socket.getInputStream());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
String line;
File file = new File("/sdcard/aaa.png");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOut = new FileOutputStream(file);
System.out.println("Getting first file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("First file finished");
fileOut.flush();
fileOut.close();
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
file = new File("/sdcard/aaa1.png");
if (!file.exists()) {
file.createNewFile();
}
fileOut = new FileOutputStream(file);
System.out.println("Getting second file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("Second file finished");
fileOut.flush();
fileOut.close();
input.close();
output.close();
}
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
finally {
try {
Log.d("ClientActivity", "Socket: Closed.");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thanks...
setReuseAddress(true) prior to binding the socket allows the socket to be bound even though a previous connection is in a timeout state.
documentation of setReuseAddress
I don't see sense in directly using socket for HTTP communication. I use HttpURLConnection. Works without problems in most cases.
Related
I am opening an SSLSocket on the client side to connect to the server.
But trying to get the socket.getOutputStream() blocks the code, without outputting any errors.
I am flushing both streams, but it still doesn't work.
Server:
SSLSocket socket = (SSLSocket) serverSocket.accept();
socket.setUseClientMode(false);
try{
socket.setSoTimeout(0);
socket.setKeepAlive(true);
socket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println("Setup"); writer.flush();
while(running){
if(!socket.isConnected() || socket.isClosed()){
disconnect();
return;
}
for(Iterator<String> pendingIterator = pendingMessages.iterator(); pendingIterator.hasNext();){
String message = pendingIterator.next();
pendingIterator.remove();
writer.println(message); writer.flush();
}
//Auto decrypt when message arrives, but no thread blocking
if(reader.ready()){
String line = reader.readLine();
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
});
socket.startHandshake();
}catch(Exception e){
e.printStackTrace();
disconnect();
}
Client:
socket.addHandshakeCompletedListener(new HandshakeCompletedListener(){
#Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent){
try{
Log.i("Update", "Did handshake");
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.flush();
Log.i("Update", "Writer");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("Update", "Reader");
while(isRunning){
try{
writer.println("Test");
writer.flush();
Log.i("DATA", "DATA SENT");
}catch(Exception e){
e.printStackTrace();
}
}
writer.close();
reader.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
socket.startHandshake();
You are misusing the handshake completed listener. Its purpose is to let to check he peer certificate, negotiated cipher suite, etc. Not to carry out the transaction. Remove it all and put it inline. You don't need even to call startHandshake(). It will happen automatically on the first I/O.
I tried to write a simple program that runs a server and then accepts two clients. Then one of them tries to send a string to another client.
but my code doesn't work and I don't know why.
This is my TestClient class:
public class TestClient extends Thread{
int id;
String Name;
Socket client;
boolean isAsk;
public TestClient(int id,String clientName,boolean isAsk) throws IOException {
this.id=id;
this.Name=clientName;
this.isAsk=isAsk;
}
public void connectTheClientToTheLocalHost(ServerSocket server){
try {
client = new Socket("localhost",1111);
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFromTerminal(){
try {
InputStream is=client.getInputStream();
OutputStream os = client.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("sdklfsdklfk");
pw.flush();
pw.close();
}catch (IOException e){
e.printStackTrace();
}
}
public void closeTheCientSocket(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(){
try {
Scanner sc = new Scanner(client.getInputStream());
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("file1.txt")));
String st =sc.nextLine();
bw.write(st);
bw.close();
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
if(isAsk){
readFromTerminal();
}
else{
write();
}
}
and this is the main function:
public class PCServer {
public static void main(String[] args){
try {
ServerSocket s = new ServerSocket(1111);
TestClient t1=(new TestClient(1,"reza",true));
TestClient t2=(new TestClient(2,"man",false));
t1.connectTheClientToTheLocalHost(s);
t1.start();
Scanner sc = new Scanner(t1.client.getInputStream());
String st=sc.nextLine();
System.out.println(st);
t1.closeTheCientSocket();
t2.connectTheClientToTheLocalHost(s);
PrintWriter pw = new PrintWriter(t2.client.getOutputStream());
pw.println(st);
pw.flush();
t2.start();
t2.closeTheCientSocket();
}catch (Exception e){
e.printStackTrace();
}
}
}
actually this code returns an exception in
String st=sc.nextLine();
in main function and says that there is no line found.
what is the problem?
ServerSocket in java usually used in another way.
If you need point-to-point connection, one host creates a ServerSocket and accepts connections. Examples:
First host example:
try(ServerSocket serverSocket = new ServerSocket(5555);
Socket socket = serverSocket.accept();
// it more convenient to use DataInputStream instead of Scanner I think
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got request: " + msg);
dataOutputStream.writeUTF("1-response");
dataOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
Second host example:
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("2-request");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got response: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
If you want one host talk to another over the server (broker), then you need plane java Sockets on hosts and ServerSocket on broker, and broker must transmit messages it received from one host to another. Examples:
Broker (run it in separate thread or process)
try {
List<Socket> sockets = new ArrayList<>();
ServerSocket serverSocket = new ServerSocket(5555);
// accepting connections from 2 clients
for (int i = 0; i < 2; i++) {
Socket socket = serverSocket.accept();
sockets.add(socket);
}
// streams for first host
InputStream hostOneInputStream = sockets.get(0).getInputStream();
DataInputStream hostOneDataInputStream = new DataInputStream(sockets.get(0).getInputStream());
DataOutputStream hostOneDataOutputStream = new DataOutputStream(sockets.get(0).getOutputStream());
// streams for second host
InputStream hostTwoInputStream = sockets.get(1).getInputStream();
DataInputStream hostTwoDataInputStream = new DataInputStream(sockets.get(1).getInputStream());
DataOutputStream hostTwoDataOutputStream = new DataOutputStream(sockets.get(1).getOutputStream());
while (!Thread.currentThread().isInterrupted()) {
if (hostOneInputStream.available() > 0) {
String msg = hostOneDataInputStream.readUTF();
System.out.println("got message from host 1: " + msg);
hostTwoDataOutputStream.writeUTF(msg);
hostTwoDataOutputStream.flush();
System.out.println("message " + msg + " sent to host two");
}
if (hostTwoInputStream.available() > 0) {
String msg = hostTwoDataInputStream.readUTF();
System.out.println("got message from host 2: " + msg);
hostOneDataOutputStream.writeUTF(msg);
hostOneDataOutputStream.flush();
System.out.println("message " + msg + " sent to host one");
}
}
} catch (IOException e) {
e.printStackTrace();
}
First host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("1");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Second host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
dataOutputStream.writeUTF("2");
dataOutputStream.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
I am naive to this socket programming. I am trying to print the content of the file present in the directory in the server's console but the server is not able to locate the file.
Here is my code:
myClient.java
import java.net.*;
import java.io.*;
public class myClient {
public static void main(String args[]){
Socket socket = null;
String hostName,command,fileName;
int port;
if(args.length == 0){
System.out.println("Error: command line arguments (hostname,port,command,"
+ "filename) not found.\nTry again...!!!");
System.exit(1);
}
hostName = args[0];
port = Integer.parseInt(args[1]);
command = args[2];
fileName = args[3];
try{
socket = new Socket(hostName,port);
System.out.println("Client Socket Created..!!");
// creating input and output streams to read from and write to the server
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
if(command.equals("GET")){
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
String line = br.readLine();
while(line != null){
System.out.println("Server: "+line);
line = br.readLine();
}
}
if(command.equals("PUT")){
System.out.println("Client: "+fileName+" sent to server");
bw.write(fileName);
// pass the file contents
bw.flush();
System.out.println("Server: "+br.readLine());
}
}
catch(UnknownHostException uhe){
System.out.println("Unknown Host...!!!");
System.exit(1);
}
catch(IOException e){
e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
myServer.java
import java.net.*;
import java.io.*;
public class myServer {
static Socket socket;
public static void main(String args[]){
try {
int port = Integer.parseInt(args[0]);
//String fileName = "";
ServerSocket server = new ServerSocket(port);
while(true)
{
System.out.println("Server started and listening on port "+port);
socket = server.accept();
System.out.println("received a connection :"+socket);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write("Echo server 1.1\n");
bw.flush();
String line = br.readLine();
while(line != null){
bw.write("Echo: "+line);
bw.flush();
line = br.readLine();
}
}
} catch (IOException e) {
System.out.println("No conncetion established");
System.exit(0);
//e.printStackTrace();
}
finally
{
//Closing the socket
try{
socket.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
Kindly help me out finding a solution to this. I have tried many examples browsing different websites but not get to the solutions.
System.out.println("Client: GET "+fileName+" HTTP/1.1\n");
bw.write(fileName);
You aren't writing a correct HTTP command to the server. You're only sending the filename, not a complete command such as the GET command you're printing to the console.
The line terminator in HTTP is specified as \r\n, not \n.
You're also making no attempt to implement other aspects of HTTP 1.1 correctly, such as content-length. If you're going to implement HTTP you need a good knowledge of RFC 2616.
If possible you should throw this away and use HttpURLConnection.
After creating socket connection in Android App, i can't write in buffer after reading.
This is an example for establishing connection with my Server:
//...
try{
socket = new Socket(IP, Port);
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
//ask for connection
out.println(req1);
//server send me a nonce
result=in.readLine().toString();
//encrypting nonce with specific alghorithm
passwd=Password.get_Passwd(result);
//sending password
out.println(passwd); //here out.println doesn't write
//...
} catch (IOException e){
e.printStackTrace();
} finally {
try {
socket.close();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//...
So can any one help me solving this problem. Thanks.
what's wrong with my code?
sorry about my bad English
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Server: client said-> "+ line);
}
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!");
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!");
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Client: server said-> "+ line);
}
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Clientrver: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Server: stream done
Server: reading the request
Client: stream done
Client: requesting
Client: requesting finished
Client: reading the respond
and it waits here forever!
The program is using a BufferedWriter but this is not flushed (it will sit in the buffer until it is flushed, the buffer fills or closed) and there is no newline sent (the readLine will wait until you send a newline)
try
bw.write("I am the Client!!\n");
bw.flush();
Both threads hang on while((line =br.readLine()) != null)
now it works
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
line = br.readLine();
System.out.println("Server: client said-> "+ line);
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
line =br.readLine();
System.out.println("Client: server said-> "+ line);
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Client: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Client: stream done
Server: stream done
Server: reading the request
Client: requesting
Client: requesting finished
Client: reading the respond
Server: client said-> Hi! I am Client!
Server: reading fished
Server: responding
Server: responding finished
Server: is finishing
Client: server said-> Hi! I am server!
Client: reading fished
Client: is finishing
Client: done
Server: done
Main done