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.
Related
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());
}
}
}
}`
I have a client and server set up in a project but they are not connecting between computers on my network.
the client:
public class GameClient extends Thread {
private static Image image;
private InetAddress ipAddress;
private DatagramSocket socket;
private Play play;
public GameClient(Play play, String ipAddress){
this.play = play;
try {
this.socket = new DatagramSocket();
this.ipAddress = InetAddress.getByName(ipAddress);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public GameClient(Play play, InetAddress ipAddress){
this.play = play;
try {
this.socket = new DatagramSocket();
this.ipAddress = ipAddress;
} catch (SocketException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
//boolean run = true;
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
}
public static void getImage(Image newImage){
image = newImage;
}
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet00Login)packet).getUsername() + " has joined the game");
PlayerMP player = new PlayerMP(((Packet00Login)packet).getUsername(), (double)200, (double)200, 65, 285, (float)0, (double)1, image, address, port);
play.addEntity(player);
play.setClientPlayer(player);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect)packet).getUsername() + " has left the world...");
play.removePlayerMP(((Packet01Disconnect)packet).getUsername());
break;
case MOVE:
packet = new Packet02Move(data);
handleMove((Packet02Move) packet);
}
}
public void sendData(byte[] data){
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, 1331);
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
private void handleMove(Packet02Move packet){
this.play.movePlayer(packet.getUsername(), packet.getX(), packet.getY(), packet.getDirection());
}
}
the server:
public class GameServer extends Thread {
private static Image image;
private DatagramSocket socket;
private Play play;
private List<PlayerMP> connectedPlayers = new ArrayList<PlayerMP>();
public GameServer(Play play){
this.play = play;
try {
this.socket = new DatagramSocket(1331);
} catch (SocketException e) {
e.printStackTrace();
}
}
public static void getImage(Image newImage){
image = newImage;
}
public void run() {
while(true) {
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data, data.length);
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
this.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
}
}
private void parsePacket(byte[] data, InetAddress address, int port) {
String message = new String(data).trim();
PacketTypes type = Packet.lookupPacket(message.substring(0, 2));
Packet packet = null;
switch (type) {
default:
case INVALID:
break;
case LOGIN:
packet = new Packet00Login(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet00Login)packet).getUsername() + " has connected to the server...");
PlayerMP player = new PlayerMP(((Packet00Login)packet).getUsername(), (double)200, (double)200, 65, 285, (float)0, (double)1, image, address, port);
this.addConnection(player, (Packet00Login)packet);
break;
case DISCONNECT:
packet = new Packet01Disconnect(data);
System.out.println("[" + address.getHostAddress() + ":" + port + "] " + ((Packet01Disconnect)packet).getUsername() + " has left...");
this.removeConnection((Packet01Disconnect)packet);
break;
case MOVE:
packet = new Packet02Move(data);
//System.out.println(((Packet02Move)packet).getUsername() + " has moved to " + (int)((Packet02Move)packet).getX() + " , " + (int)((Packet02Move)packet).getY());
this.handleMove(((Packet02Move)packet));
break;
}
}
public void addConnection(PlayerMP player, Packet00Login packet) {
boolean alreadyConnected = false;
if(!this.connectedPlayers.isEmpty()){
for(PlayerMP p: this.connectedPlayers){
if(player.getUsername().equalsIgnoreCase(p.getUsername())){
System.out.println("Client " + player.getUsername() + " already conected as " + p.getUsername() + ": updating player information");
if(p.getIpAddress() == null){
p.setIpAddress(player.getIpAddress());
}
if(p.getPort() == -1){
p.setPort(player.getPort());
}
alreadyConnected = true;
}else{
// relay to the current connected player that there is a new
// player
sendData(packet.getData(), p.getIpAddress(), p.getPort());
// relay to the new player that the currently connect player
// exists
packet = new Packet00Login(p.getUsername());
System.out.println("Sending already conected player to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
sendData(packet.getData(), player.getIpAddress(), player.getPort());
}
}
}else{
System.out.println("Sending login to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
sendData(packet.getData(), player.getIpAddress(), player.getPort());
this.connectedPlayers.add(player);
alreadyConnected = true;
}
if(!alreadyConnected){
System.out.println("Sending login to [" + player.getIpAddress().getHostAddress() + ":" + player.getPort() + "] " + player.getUsername());
packet = new Packet00Login(player.getUsername());
sendData(packet.getData(), player.getIpAddress(), player.getPort());
this.connectedPlayers.add(player);
}
}
public void removeConnection(Packet01Disconnect packet) {
this.connectedPlayers.remove(getPlayerMPIndex(packet.getUsername()));
packet.writeData(this);
}
public PlayerMP getPlayerMP(String username){
for(PlayerMP player : this.connectedPlayers){
return player;
}
return null;
}
public int getPlayerMPIndex(String username){
int index = 0;
for(PlayerMP player : this.connectedPlayers){
if(player.getUsername().equals(username)){
break;
}
index++;
}
return index;
}
public void sendData(byte[] data, InetAddress ipAddress, int port) {
DatagramPacket packet = new DatagramPacket(data, data.length, ipAddress, port);
try {
this.socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendDataToAllClients(byte[] data) {
for (PlayerMP p : connectedPlayers) {
sendData(data, p.getIpAddress(), p.getPort());
}
}
private void handleMove(Packet02Move packet){
if(getPlayerMP(packet.getUsername()) != null){
int index = getPlayerMPIndex(packet.getUsername());
this.connectedPlayers.get(index).x = packet.getX();
this.connectedPlayers.get(index).y = packet.getY();
((PlayerMP)this.connectedPlayers.get(index)).playerDirection = packet.getDirection();
packet.writeData(this);
}
}
}
here is where it sends the first login packet to the server from my play class (this packet is not being received)
if(JOptionPane.showConfirmDialog(null, this, "do you want to start the server?", mousePosX) == 0){
socketServer = new GameServer(this);
socketServer.start();
}
try {
socketClient = new GameClient(this, InetAddress.getLocalHost());
} catch (UnknownHostException e) {
e.printStackTrace();
}
socketClient.start();
GameClient.getImage(standing);// these are just so that the client and the server have the image to create the player entity once they join the game
GameServer.getImage(standing);
Packet00Login loginPacket = new Packet00Login(Global.playerUsername);
loginPacket.writeData(socketClient); //this is where the first login is being sent, it is not being received.
To be clear the program works localy on one computer and the ip's look correct (192.0.0.XXX) but when i chose to run the server on one computer and not on the other the second computer does not connect to the first.
thanks in advance!
Figured it out, wasent anything to do wit the net work :P turns out i was accidently calling the server directly to send information rather than the client. Moved the server to a new project and set it up as a stand alone as I should have done in the first place and everything works great :). Thanks for the help though!
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();
}
}
I"m working on a Client-Server chat program for a university project and I have little programming background. I've made 3 classes: ChatClient, ChatServer and ChatServerThread. I can currently have multiple clients connected and talking to the server at any time.
Although one of the requirements that I'm having the most difficulty is this: "Any message typed from 1 client is sent to all other clients" and also "Both sent and received messages should be displayed".
I've spent the last few nights just trying to get this extra bit of functionality working but have had no luck.
I've been reading and looking around for a while but I have lots of difficulty adapting online examples to my work. I've read that I should be creating a list of sockets and then iterate through the list and send data to everyone in the list, which makes sense in my head but gives me a headache when I try implementing it. Any help with this would be very greatly appreciated. Extra points if anyone can give me some insight on how I could encrypt the sent data.
ChatClient
import java.net.*;
import java.io.*;
public class ChatClient {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private String myName = null;
private BufferedReader StreamIn = null;
private String response = null;
public ChatClient(String serverName, int serverPort) {
try {
console = new DataInputStream(System.in);
System.out.println("What is your name?");
myName = console.readLine();
System.out.println(myName + " <" + InetAddress.getLocalHost() + "> ");
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
StreamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
streamOut = new DataOutputStream(socket.getOutputStream());
streamOut.writeUTF(":" + myName + " <" + InetAddress.getLocalHost() + "> HAS JOINED");
streamOut.flush();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals(".bye")) {
try {
line = console.readLine();
streamOut.writeUTF(myName + " <" + InetAddress.getLocalHost() + "> : " + line);
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void stop() {
try {
if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public static void main(String args[]) {
ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}
ChatServer
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer implements Runnable {
private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
private String clientSentence = null;
private int peers = 0;
private List clients = new ArrayList();
final List sockets = new ArrayList();
public ChatServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void run() {
while (thread != null) {
try {
System.out.println("Waiting for a client ...");
addThread(server.accept());
} catch (IOException ie) {
System.out.println("Acceptance Error: " + ie);
}
}
}
public void addThread(Socket socket) {
System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try {
client.open();
client.start();
} catch (IOException ioe) {
System.out.println("Error opening thread: " + ioe);
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
if (thread != null) {
thread.stop();
thread = null;
}
}
public void increment(String sentence) {
peers++;
String[] info = sentence.split(" ");
String name = info[0].replace(":", "");
System.out.println(name + " Has joined the room, we now have " + peers + " peer(s).");
clients.add(name);
}
public Boolean isAllowed(String name, Socket socket) {
try {
String stringSearch = name;
BufferedReader bf = new BufferedReader(new FileReader("allowed.txt"));
int linecount = 0;
String line = "";
System.out.println("Searching for " + stringSearch + " in file...");
while ((line = bf.readLine()) != null) {
linecount++;
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(stringSearch)) {
System.out.println("User is allowed");
registerSocket(socket);
return true;
}
}
}
bf.close();
} catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
System.out.println("User is not allowed");
return false;
}
public void showAll() {
for (int i = 0; i < clients.size(); i++) {
System.out.print(clients.get(i));
}
}
public void registerSocket(Socket socket) {
//socket = new DataOutputStream(socket.getOutputStream());
sockets.add(socket);
for (int i = 0; i < sockets.size(); i++) {
System.out.println(sockets.get(i));
}
}
public static void main(String args[]) {
ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
ChatServerThread
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread {
private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;
private String clientSentence = null;
public String newGuy = null;
DataOutputStream streamOut = null;
public ChatServerThread(ChatServer _server, Socket _socket) {
server = _server;
socket = _socket;
ID = socket.getPort();
}
public void run() {
System.out.println("Server Thread " + ID + " running.");
while (true) {
try {
String sentence = streamIn.readUTF();
//System.out.println(sentence);
char c = sentence.charAt(0);
String[] command = null;
command = sentence.split(" ");
String name = command[0].substring(1);
System.out.println("Sending out: " + sentence + " via ");
streamOut.writeBytes(sentence);
if (c == ':') {
if (server.isAllowed(name, socket))
server.increment(sentence);
else {
close();
}
}
} catch (IOException ioe) {
}
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}
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");
}
}