How to read or print the BufferedReader ( InputStreamReader) - java

I´m creating a new socket to send a string through the socket, then the socket generates a reply (I monitor the reply in Wireshark) but in the code I cannot see any answer, only if I connect again to the socket with another app, then I receive the answer in the first socket connection.
public class TCPConnections
{
public static void main (String[] args) throws Exception
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
String response = "";
String hostGreetings = "<frame><cmd><id>5</id><hostGreetings><readerType>SIMATIC_RF680R</readerType><supportedVersions><version>V2.0</version></supportedVersions></hostGreetings></cmd></frame>\n";
String getReaderStatus = "<frame><cmd><id>2</id><getReaderStatus></getReaderStatus></cmd></frame>\n";
StringBuilder antwort = new StringBuilder();
int c;
int counter = 0;
try
{
String host = "30S50RFID01.w30.bmwgroup.net";
int port = 10001;
InetAddress address = InetAddress.getByName(host);
System.out.println("adress: " + address);
socket = new Socket(address, port);
System.out.println("Socket connected: " + socket.isConnected());
System.out.println("Remote Port: " + socket.getPort());
System.out.println("Traffic Class: " + socket.getTrafficClass());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//byte [] bytes = hostGreetings.getBytes("UTF-8");
//System.out.println("UTF-8 = "+bytes);
if (socket.isConnected())
{
out.println(hostGreetings);
System.out.println("Message send:" + hostGreetings);
System.out.println("Message send:" + socket.getOutputStream());
System.out.println("Greeting sent, waiting for response");
Thread.sleep( 2000 );
boolean reading = true;
while (reading) {
if(in.ready ()){
c = (char) in.read();
response = response + c;
System.out.println("Reply" + response);
}else {
reading = false;
}
}
}
}
else
{
System.out.println("Socket connected: " + socket.isConnected());
}
}
catch (IOException ex)
{
System.out.println("Error 1: " + ex.getMessage());
}
catch (InterruptedException ex)
{
Logger.getLogger(TCPConnections.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{//Closing the socket
try
{
System.out.println("Connection will be closed and program terminated");
out.close();
in.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("Error 2: " + ex.getMessage());
}
}
}
}`

Related

Java socket client not connected to server

I get this error from my server when I call the the search animal's method. The
client connects to the server but as soon as I have clicked on the search method I get the following ERROR:
CONNECTED. getConnection
ServerConnect, searchAnimal: java.net.SocketException: Socket is not
connected
CONNECTED. getConnection
getConnection is the method to connect to database and sockets. I don't know how to fix it. Help please!
These are my declarations. I put the GUI and Server into one page of code:
public class MGLser5 extends JFrame { //declarations
static private JTextArea txtWin = new JTextArea();
private JScrollPane sp = new JScrollPane(txtWin);
private JButton clear = new JButton();
private int port;
Socket soc; //client socket
ServerSocket lstn; //server socket
InputStream in;
DataInputStream inData;
OutputStream out;
DataOutputStream outData;
static String client, username, password, request;
boolean connected;
static String model;
static Connection conn;
static Statement st;
static ResultSet rec;
private void startServer() {
try {
lstn = new ServerSocket(port);
txtWin.append("Listening on port number: " + port + "\n");
soc = lstn.accept();
connected = true;
in = soc.getInputStream();
inData = new DataInputStream(in);
out = soc.getOutputStream();
outData = new DataOutputStream(out);
//client = lstn.accept();
client = inData.readUTF();
txtWin.append("Connection established with " + client + "\n");
while (connected) {
model = "";
request = inData.readUTF();
txtWin.append("Request from client: \t" + request + "\n");
//db/socket disconnect
if ("Exit".equals(request)) {
try {
connected = false;
soc.close();
lstn.close();
in.close();
inData.close();
out.close();
outData.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MGLser5.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
delegate(request);
}
}
} catch (IOException ex) {
txtWin.append("Start Server 2: " + ex.getMessage() + "\n");
}
data base connection
public static void executeQ(String query) {
try {
connectDb();
st = conn.createStatement();
// Result set returned for a simple query
rec = st.executeQuery(query);
} catch (SQLException ex) {
txtWin.append("executeQ: " + ex.getMessage() + "\n");
}
}
constructor
public MGLser5(int portIn) {
super("Mokgele Game Lodge ");
port = portIn;
add("Center", sp);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(exitListener);
setSize(400, 300);
setVisible(true);
startServer();
}
search animal method
try {
String result = "";
while (connected) {
boolean match = Pattern.matches("[a-z]+", search);
if (!match || !"".equalsIgnoreCase(search)) {
connectDb();
java.sql.Statement stmt = conn.createStatement();
String sql1 = "SELECT * FROM Animals WHERE animal_name LIKE '%" + search + "%'";
String sql2 = "SELECT * FROM Species WHERE species_name LIKE '%" + search + "%'";
String sql3 = "SELECT Animal.* FROM Species INNER JOIN Animal ON Species.species_id = Animal.species_id WHERE (Species.species_name)=\'" + search + "\';";
ResultSet rs = stmt.executeQuery(sql1);
while (rs.next()) {
result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name: " + rs.getString(2) + "\nInfo: " + rs.getString(3) + "\nSpecies ID: " + rs.getString(4);
result += "\n";
}
//If there's nothing in the Animal table, check the Species table
rs = stmt.executeQuery(sql2);
while (rs.next()) {
result += "\nID: " + rs.getString(1) + "\nSpecies Name: " + rs.getString(2);
result += "\n";
}
//Search for all the records of one classification, like all the felines or rodents
rs = stmt.executeQuery(sql3);
while (rs.next()) {
result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name: " + rs.getString(2) + "\nInfo: " + rs.getString(3) + "\nSpecies ID: " + rs.getString(4);
result += "\n";
}
return result;
} else /*Error mssage for wrong search input*/ {
JOptionPane.showMessageDialog(null, "Error.\nPlease ReEnter your search agian");
return "";
}
}
return result;
} catch (SQLException e) {
System.out.println("Server, SearchAnimal: " + e);
connected = false;
return "";
}
Client server
//DECLARATIONS
private Socket clientSocket = new Socket();
private DataInputStream Datain;
private InputStream in;
private DataOutputStream Dataout;
private OutputStream out;
static private String server = "127.0.0.1", host;//local host
final int portIn = 8888;//port number
boolean isConnect = true;
public DataInputStream getInData() {
return Datain;
}
public DataOutputStream getOutData() {
return Dataout;
}
//CLIENT CONNECTIONS
public void getConnection() {
try {
//ServerSocket svrSoc = null;
clientSocket = new Socket(server, portIn);
//svrSoc = new ServerSocket(portIn);
//clientSocket = svrSoc.accept();
//Input stream from the server
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
//Output stream to the server
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
Dataout.writeUTF(host);
System.out.println("CONNECTED. getConnection");
//closeConnection();
} catch (IOException e) {
System.out.println("ServerConnect, getConnection1: " + e);
//closeConnection();
} catch (NullPointerException e) {
System.out.println("ServerConnect, getConnection2: " + e);
//closeConnection();
}
}
private void getNewConnection(String request) {//send and receive data
try {
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
host = request;
Dataout.writeUTF(host);
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
//Method to close the connection
public void closeConnection() {
try {
clientSocket.close();
Datain.close();
Dataout.close();
clientSocket.close();
System.out.println("DISCONNECTED .");
} catch (IOException e) {
System.out.println("ServerConnect, closeConnection: " + e);
} catch (NullPointerException e) {
System.out.println("ServerConnect, closeConnection: " + e);
}
}
//Method for Search method in Server
public String searchAnimal(String search) {
String fromServer;
try {
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
if (isConnect) {
Dataout.writeUTF("searchAnimal");
Dataout.writeUTF(search);
fromServer = Datain.readUTF();
//closeConnection();
return fromServer;
} else {
System.out.println("ERROR SEARCH ANIMAL NOT FUNCTIONING ");
}
//closeConnection();
return "";
} catch (IOException e) {
System.out.println("ServerConnect, searchAnimal: " + e);
//closeConnection();
return "";
} catch (NullPointerException e) {
System.out.println("ServerConnect, searchAnimal: " + e);
//closeConnection();
return "";
}
}
private Socket clientSocket = new Socket();
The problem is here. You are creating an unconnected socket, which is pointless, and then never connecting it.

Chat server client sometimes cannot see message from other clients on the same server

I am making 2 classes for Chat server client for a project I am working on. The problem is server can see the message that sent to it(from client) and it can send those messages out to every clients BUT each client has to type in some input first if he wants to see the message from other users. I have no clue what I did wrong. Please help me out. Thanks in advance :)
Server Class
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class TestServer extends Thread
{
protected Socket clientSocket;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
final static int PORT = 22;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
System.out.println ("Connection Socket Created");
try
{
while (true)
{
System.out.println ("Waiting for Connection");
Socket sock = serverSocket.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
new TestServer (sock);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private TestServer (Socket inSock)
{
clientSocket = inSock;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
//System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while (true)
{
inputLine = in.readLine();
System.out.println ("Server: " + inputLine);
for(int i = 1; i <= TestServer.ConnectionArray.size(); i++)
{
System.out.println("Total Connection: " + ConnectionArray.size());
Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i-1);
if (clientSocket != TEMP_SOCK)
{
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
TEMP_OUT.println(inputLine);
TEMP_OUT.flush();
System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
}
}
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client Class
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname);
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 22);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("Other user: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need a separate thread in the client for reading from the server without blocking on System.in;
Thread t = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Other user: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
}
t.interrupt();

why do network socket connect and send/recieve data takes long in wireless?

I made an app client in android device (with ethernet and wireless port) and server application in windows.
Data transfers via Socket programming between devices and when i test it in emulator in PC or run in Ethernet via cable it works correctly, but when i connect server and client with wireless connectivity (via an access point) data sent or received with a delay . this delay may be take over 60 seconds !
i don't know why this problem happend !
This is my sending routin in android :
Server_Port = mDbHelper.GetPortNumber();
//mDbHelper.close();
final String Concatinate_values = firstByte_KindType + Spliter + secoundByte_KindofMove +
Spliter + ValueOfMove + Spliter + valueOfsetting + Spliter + MaxOrMinValue;
//Sent Routin
////‌Connect To server
Thread thread = null;
thread = new Thread(new Runnable() {
#Override
public void run() {
DataOutputStream outputStream = null;
BufferedReader inputStream = null;
Socket socket;
socket = new Socket();
try {
socket.connect(new InetSocketAddress(Server_IP, Server_Port), 10);
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
Thread.currentThread().interrupt();
}
////Make Read Line
try {
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e1) {
//Finished Socket
ShutDown(socket);
}
if (outputStream == null) {
//
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
//Write Message
try {
String message = Concatinate_values + "\n";
outputStream.write(message.getBytes());
outputStream.flush();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
catch (IOException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
try {
if (socket != null) {
socket.close();
}
}
catch (IOException e) {
e.printStackTrace();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
Thread.currentThread().interrupt();
}
});
thread.start();
My windows server code in c# :
class Program
{
static Socket socketForClient;
static NetworkStream networkStream;
static System.IO.StreamReader streamReader;
static System.IO.StreamWriter streamWriter;
static TcpListener tcpListener;
static int PORT;
static void Main(string[] args)
{
//Console.WriteLine("Enter Port : ");
//PORT = Convert.ToInt32(Console.ReadLine());
PORT = 12500;
Console.WriteLine("\n" + "Your Host Information Is : "+"\n" );
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in localIPs)
{
Console.WriteLine(ip.ToString());
}
while (true)
{
tcpListener = new TcpListener(PORT);
Console.WriteLine("\n >> Server started ... Waiting for Message");
tcpListener.Start();
try
{
socketForClient = tcpListener.AcceptSocket();
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 40");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
if (socketForClient.Connected)
{
Console.WriteLine("Client connected");
try
{
networkStream = new NetworkStream(socketForClient);
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 55");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
//System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
try
{
streamReader = new System.IO.StreamReader(networkStream);
streamWriter = new System.IO.StreamWriter(networkStream);
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 71");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
string theString = "Sending";
// streamWriter.WriteLine(theString);
Console.WriteLine(theString);
//streamWriter.Flush();
long x = 0;
try
{
x++;
theString = streamReader.ReadLine();
if (theString.Trim() == "4-")
{
Console.WriteLine("Sending Report Data : 0-100-0-0");
streamWriter.WriteLine("0-70-0-0");
Console.WriteLine("pocket sent");
streamWriter.Flush();
}
Console.WriteLine(theString + x.ToString());
streamReader.Close();
networkStream.Close();
socketForClient.Close();
tcpListener.Stop();
}
catch (System.Exception e1)
{
streamReader.Close();
networkStream.Close();
socketForClient.Close();
Console.WriteLine("LN: 97");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
break;
//streamWriter.Close();
}
}
}
streamReader.Close();
networkStream.Close();
socketForClient.Close();
Console.WriteLine("Closed Socket");
Console.ReadLine();
}
}

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

How to redirect to locally stored index.html file when localhost:<port> is called from a browser

I am creating a socket server in android. I have a directory in my local storage in which there is index.html and all other resources needed. I want that when i start the socket server and then call localhost: from my mobile's browser then it redirects to the index.html.
My socket is running. the logs are printing. the issue is i don't know how to redirect to index.html.
Thanks in advance.
Below is my code:
public class Server {
MainActivity activity;
ServerSocket serverSocket;
String message = "";
static final int socketServerPORT = 8080;
public Server(MainActivity activity) {
this.activity = activity;
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.start();
}
public int getPort() {
return socketServerPORT;
}
public void onDestroy() {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("SocketServerThread.run i am running");
}
});
SocketServerReplyThread socketServerReplyThread =
new SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Server, you are #" + cnt;
final String OUTPUT = "https://www.google.com";
final String OUTPUT_HEADERS = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html; charset=UTF-8\r\n" +
"date: Fri, 25 Oct 2019 04:58:29 GMT"+
"Content-Length: ";
final String OUTPUT_END_OF_HEADERS = "\r\n\r\n";
try {
outputStream = hostThreadSocket.getOutputStream();
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
new BufferedOutputStream(outputStream),"UTF-8" ));
out.write(OUTPUT_HEADERS + OUTPUT.length() + OUTPUT_END_OF_HEADERS + OUTPUT);
out.flush();
out.close();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("Here is another message for you " + message);
}
});
}
}
public String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress
.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "Server running at : "
+ inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
}
Finally I got the solution to my problem here it is
static final File WEB_ROOT = new File("<your files path>");
static final String DEFAULT_FILE = "index.html";
static final String FILE_NOT_FOUND = "404.html";
static final String METHOD_NOT_SUPPORTED = "not_supported.html";
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
// create ServerSocket using specified port
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
// block the call until connection is created and return
// Socket object
Socket socket = serverSocket.accept();
connect = socket;
count++;
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
System.out.println("SocketServerThread.run i am running");
}
});
JavaHTTPServer.SocketServerReplyThread socketServerReplyThread =
new JavaHTTPServer.SocketServerReplyThread(socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {// we manage our particular client connection
BufferedReader in = null;
PrintWriter out = null;
BufferedOutputStream dataOut = null;
String fileRequested = null;
try {
// we read characters from the client via input stream on the socket
in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
// we get character output stream to client (for headers)
out = new PrintWriter(connect.getOutputStream());
// get binary output stream to client (for requested data)
dataOut = new BufferedOutputStream(connect.getOutputStream());
// get first line of the request from the client
String input = in.readLine();
System.out.println("SocketServerReplyThread.run input " + input);
// we parse the request with a string tokenizer
if (input == null)
return;
StringTokenizer parse = new StringTokenizer(input);
System.out.println("SocketServerReplyThread.run parse " + parse);
String method = parse.nextToken().toUpperCase(); // we get the HTTP method of the client
System.out.println("SocketServerReplyThread.run method " + method);
// we get file requested
fileRequested = parse.nextToken().toLowerCase();
if (fileRequested.contains("?"))
fileRequested = fileRequested.split("\\?")[0];
System.out.println("SocketServerReplyThread.run fileRequested " + fileRequested);
// we support only GET and HEAD methods, we check
if (!method.equals("GET") && !method.equals("HEAD")) {
if (verbose) {
System.out.println("501 Not Implemented : " + method + " method.");
}
// we return the not supported file to the client
File file = new File(WEB_ROOT, METHOD_NOT_SUPPORTED);
int fileLength = (int) file.length();
String contentMimeType = "text/html";
//read content to return to client
byte[] fileData = readFileData(file, fileLength);
// we send HTTP Headers with data to client
out.println("HTTP/1.1 501 Not Implemented");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + contentMimeType);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
// file
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
} else {
// GET or HEAD method
if (fileRequested.endsWith("/")) {
fileRequested += DEFAULT_FILE;
}
File file = new File(WEB_ROOT, fileRequested);
int fileLength = (int) file.length();
String content = getContentType(fileRequested);
if (method.equals("GET")) { // GET method so we return content
byte[] fileData = readFileData(file, fileLength);
// send HTTP Headers
out.println("HTTP/1.1 200 OK");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
}
if (verbose) {
System.out.println("File " + fileRequested + " of type " + content + " returned");
}
}
} catch (FileNotFoundException fnfe) {
try {
fileNotFound(out, dataOut, fileRequested);
} catch (IOException ioe) {
ioe.printStackTrace();
System.err.println("Error with file not found exception : " + ioe.getMessage());
}
} catch (IOException ioe) {
System.err.println("Server error : " + ioe);
} finally {
try {
in.close();
out.close();
dataOut.close();
connect.close(); // we close socket connection
} catch (Exception e) {
System.err.println("Error closing stream : " + e.getMessage());
}
if (verbose) {
System.out.println("Connection closed.\n");
}
}
}
}
private byte[] readFileData(File file, int fileLength) throws IOException {
FileInputStream fileIn = null;
byte[] fileData = new byte[fileLength];
try {
fileIn = new FileInputStream(file);
fileIn.read(fileData);
} finally {
if (fileIn != null)
fileIn.close();
}
return fileData;
}
// return supported MIME Types
private String getContentType(String fileRequested) {
if (fileRequested.endsWith(".htm") || fileRequested.endsWith(".html"))
return "text/html";
else
return "text/plain";
}
private void fileNotFound(PrintWriter out, OutputStream dataOut, String fileRequested) throws IOException {
File file = new File(WEB_ROOT, FILE_NOT_FOUND);
int fileLength = (int) file.length();
String content = "text/html";
byte[] fileData = readFileData(file, fileLength);
out.println("HTTP/1.1 404 File Not Found");
out.println("Server: Java HTTP Server from SSaurel : 1.0");
out.println("Date: " + new Date());
out.println("Content-type: " + content);
out.println("Content-length: " + fileLength);
out.println(); // blank line between headers and content, very important !
out.flush(); // flush character output stream buffer
dataOut.write(fileData, 0, fileLength);
dataOut.flush();
if (verbose) {
System.out.println("File " + fileRequested + " not found");
}
}

Categories

Resources