I am writing a program to eventually make my own file server. I am having issues with connecting to the server in a web browser via typing myIpAddress:port into the browser while the server is running. This does work if I use one computer to both host the server and be a client, but does not if I use a second computer to be a client.
I have 2 classes, Index and ClientHandler
public class Index {
public static void main(String[] args) {
ServerSocket server = null;
try {
server = new ServerSocket(8080);
DevInterface myFace = new DevInterface(server);
System.out.println("Listening for connection on port 8080");
} catch (IOException e) {
e.printStackTrace();
}
int i = 0;
while(true) {
Socket client = null;
try {
client = server.accept();
ClientHandler clientHandler = new ClientHandler(client);
clientHandler.start();
System.out.println("got a client");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
and my ClientHandler class which is what sends my html to the server is this.
public class ClientHandler extends Thread{
private Socket client = null;
private PrintWriter out = null;
ArrayList<Socket> clientList = null;
public ClientHandler(Socket client) {
this.client = client;
}
public ClientHandler(Socket client, ArrayList<Socket> clientList) {
this.client = client;
this.clientList = clientList;
}
public void run() {
try {
out = new PrintWriter(client.getOutputStream());
out.println("HTTP/1.1 200 OK");
out.println("Content-Type: text/html");
out.println("\r\n");
out.println("<p>Hello World</p>");
out.flush();
out.close();
if(client!=null) {client.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Related
I am trying to create an Android Server and Client on C# base on TCP Socket. I want them both to send and received a string(Data) so I can make a command base on the given string(Data). For the meantime, the Server can listen to incoming clients and the Clients can connect to Server. But I have two problem and i can't solve it.
PROBLEMS:
1. When i try to send the data to Server, the Server was unable to Read it.
2. When the Client is Disconnected, the Server is giving me a loop of Null.
I already try to Search about communicating C# and Android using TCP but i didn't found anything like what i need.
The following code is for Android Server.
I am having a loop of Null in class CommunicationThread when the client is Disconnected. I think it's because I am using a while for reading the Data from client, but since it become disconnected then it is resulting a null.
public class MainActivity extends AppCompatActivity {
TextView tx1, tx_waiting;
private ServerSocket serverSocket;
Handler updateConversationHandler, dg;
Thread serverThread = null;
public static final int SERVERPORT = 6000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tx1 = (TextView)findViewById(R.id.textView1);
tx_waiting = (TextView)findViewById(R.id.tx_waiting);
//Start the Server
try{
updateConversationHandler = new Handler();
dg = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
tx_waiting.setVisibility(View.VISIBLE);
Log.d("Server Starting","Server Already Started.");
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
Log.d("Server Stop","Successfully Stopped the Server Without any Error.");
} catch (IOException e) {
Log.e("Server Failed to Stop",e.toString());
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
Log.d("Server Thread","Server Thread Already Started.");
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
Log.d("Server Socket","New Client is Connected");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
Log.d("Input Stream","Input Stream Received!.");
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
Log.d("Update Convers.","Conversation was Updating...");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
Log.d("Client Data",msg.toString());
}
}
}
The following code is for C# Client to Connect and Send the Data.
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
Task f = Task.Factory.StartNew(() => {
//Connect the Client into Server
try {
clientSocket.Connect(tb_ip.Text, int.Parse(tb_port.Text));
}
catch (Exception ezz) {
MessageBox.Show("Server Not Found.");
}
//Assuming that the CLient is Connected then Send a Sample Data
try {
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes("This is Sample Data");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
catch (Exception er) {
Console.WriteLine(er.ToString());
}
});
I have no method yet for Sending the Data from Server to Client since I am just starting to make this thing works, But if you have anything that can help me about this then i will really appreciate it. Thanks.
I'm writing an all-in-one java chat program which will either act as a client or a server. I'm currently having this problem where, after the connection is established, the program only successfully recieves (or sends?) some of the messages. I've used a loop to spam through a load of junk and I've seen that the other end will only pick up some of the messages. I've never got a message to send manually.
Here is the code:
public class ConnectionThread implements Runnable {
private Connection c = Connection.getInstance();
private ChatInterface chatInterface;
private static ConnectionThread serverThread;
private ServerSocket serverSocket;
private Socket socket;
private ObjectInputStream dataIn;
private ObjectOutputStream dataOut;
public ConnectionThread() {}
public static synchronized ConnectionThread getInstance() {
if (serverThread == null) {
serverThread = new ConnectionThread();
}
return serverThread;
}
public void run() {
// If the programs role is server, set up the server
if (c.getRole() == ConnectionRole.SERVER) {
try {
setupServer();
waitForConnection();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.SERVER);
}
// If the programs role is client, set up a connection to the server
if (c.getRole() == ConnectionRole.CLIENT) {
try {
setupClient();
setupStreams();
} catch (IOException e) {
e.printStackTrace();
}
do {
try {
chatInterface.addToChatHistory(dataIn.readUTF());
} catch (IOException e) {
e.printStackTrace();
}
} while (c.getRole() == ConnectionRole.CLIENT);
}
}
private void setupClient() throws IOException {
System.out.println("ATTEMPTING TO CONNECT...");
socket = new Socket("127.0.0.1", 8080);
System.out.println("CONNECTED!");
}
private void setupServer() throws IOException {
System.out.println("SETTING UP SERVER..");
serverSocket = new ServerSocket(8080, 1);
System.out.println("SERVER SETUP");
}
private void waitForConnection() throws IOException {
System.out.println("WAITING FOR A CONNECTION...");
socket = serverSocket.accept();
System.out.println("CONNECTION RECIEVED");
}
private void setupStreams() throws IOException {
System.out.println("SETTING UP STREAMS...");
dataOut = new ObjectOutputStream(socket.getOutputStream());
dataIn = new ObjectInputStream(socket.getInputStream());
chatInterface = ChatInterface.getInstance();
System.out.println("STREAMS SETUP");
}
public void sendMessage(String message) throws IOException {
System.out.println("SENDING MESSAGE...");
dataOut.writeUTF(message);
chatInterface.addToChatHistory(message);
System.out.println("MESSAGE SENT!");
}
}
Can anyone tell me why not all messages are being sent/picked up properly? I've been playing with it for quite a while now and I can't figure out why.
I found out after following EJP's recommendation to switch to DataInput/OutputStreams which worked straight away. Although I did need to be using ObjectInput/OutputStreams so I switched back. I found that I got the same issue again, until I switched to write/readObject instead of write/readUTF. If I cast the readObject to (String) it would then manage to receive every message.
So if anyone is having the same problem with ObjectInput/OutputStreams using write/readUTF try using write/readObject instead.
I am working on Socket programming. I have build such a server which should accept multiple Clients. Here I have particular num of clients , clients keeps on sending msg to Server every 10sec , Server has to process it.The problem I am having is I am unable to connect multiple Server and here a single client is a continuous running programm in while(true) So if one client Sends a request another client can not connect . Here is my Program.
Server
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private Socket s1 = null;
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
s1 = serverSocket.accept();
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
// throw new ArithmeticException();
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}
Server is working fine but I am not able to write Client program which shoud run in while(true) loop for sending msg to Server and allow other client also connect to Server.
but for a single client I write like this ,
public class SimClient extends Thread {
private Socket s1 = null;
SimClient() {
//this.start();
}
public void run() {
int i=0;
try {
s1 = new Socket("localhost", 1231);
} catch (IOException ex) {
Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
}
// while (i<10) {
try {
// Open your connection to a server, at port dfg1231
OutputStream s1out = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(s1out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Data from Client:");
String s = br.readLine();
dos.writeUTF(s);
dos.flush();
s1out.close();
dos.close();
// s1.close();
i++;
} catch (IOException ex) {
//ex.printStackTrace();
System.out.println("Exception in While: "+ex.getMessage());
}
//}
}
public static void main(String args[]) throws IOException {
SimClient s= new SimClient();
s.start();
}
}
So can any one help me to write client program. its a great help for me.
just as you have a Thread for the ServerSocket, you need to create a Thread for every Socket returned by serverSocket.accept() , then it loops back around immediately to block and wait to accept another Socket. Make a class called SocketHander which extends Thread and accepts a Socket in the constructor.
public class SocketHandler extends Thread {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
}
public void run() {
// use the socket here
}
}
and back in the ServerSocket handler...
for (;;) {
SocketHandler socketHander = new SocketHandler(serverSocket.accept());
socketHander.start();
}
It is generally a good idea to use a Fixed Size Thread Pool because creating Threads in a ad-hoc manner may cause the Server to run out of Threads if the requests are high.
public class SimpleServer extends Thread {
private ServerSocket serverSocket = null;
private static ExecutorService executor = Executors.newFixedThreadPool(100);
SimpleServer() {
try {
serverSocket = new ServerSocket(1231);
this.start();
} catch (IOException ex) {
System.out.println("Exception on new ServerSocket: " + ex);
}
}
public void run() {
while (true) {
try {
System.out.println("Waiting for connect to client");
final Socket s1 = serverSocket.accept();
executor.execute(new Runnable() {
public void run() {
try {
System.out.println("Connection received from " + s1.getInetAddress().getHostName());
InputStream s1In = s1.getInputStream();
DataInputStream dis = new DataInputStream(s1In);
String st = dis.readUTF();
System.out.println(st);
s1In.close();
dis.close();
s1.close();
} catch(Exception e) {
System.out.println("Exceptiopn: "+e);
}
// throw new ArithmeticException();
}});
} catch (IOException ex) {
Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception e) {
System.out.println("Exceptiopn: "+e);
}
}
}
public static void main(String args[]) throws IOException {
new SimpleServer();
}
}
Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?
Im sending data using BufferedWriter but this methid just seems to work for one time only, after doing the write and the flush method Im able just to send 1 message to my server, then it just doesnt get the data im sending...
Client connects - sends data to server (1st time) - Works
Client sends data again - no data echoed on server console.
Should I open a bufferedwriter each time I want to send data or keep one open all the time and never close it?
My actual code - Client side
Main
public class Main {
public static void main(String args[]) {
Client chat = new Client("localhost", 6111);
}
}
Client
public class Client {
public Client(String host, int port) {
SwingUtilities.invokeLater(new Runnable() {
private Socket chat;
public void run() {
try {
this.chat = new Socket("localhost", 6113);
} catch ( IOException e) {
e.printStackTrace();
}
Gui gui = new Gui("Chat", this.chat);
}
});
}
}
GUI
public class Gui {
private JFrame frame;
private JTextArea area;
private JTextField field;
private JMenuBar menu;
private JButton button;
private Socket socket;
private BufferedWriter write;
public Gui(String title, Socket socket) {
this.socket = socket;
try {
this.write = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
this.frame = new JFrame(title);
this.frame.setSize(new Dimension(400, 400));
this.frame.setLayout(new BorderLayout());
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
Elements interfce = new Elements(this.frame);
this.field = interfce.addField("Texto to send...");
this.menu = interfce.addBar();
this.area = interfce.addArea();
this.button = interfce.addButton("Send");
this.button.addActionListener(new Listener(this.field, this.socket, this.write));
this.menu.add(this.field);
this.menu.add(this.button);
this.frame.setVisible(true);
}
}
Listener (sends data)
public class Listener implements ActionListener {
private JTextField text;
private Socket chat;
private BufferedWriter writer;
public Listener(JTextField field, Socket chat, BufferedWriter write) {
this.text = field;
this.chat = chat;
this.writer = write;
}
public void actionPerformed(ActionEvent e) {
System.out.println(this.text.getText());
try {
writer.write("Hello\n");
writer.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
And the server
public class Main {
public static void main(String args[]) {
Server chat = new Server(6113);
}
}
public class Server {
private int port;
private ServerSocket server;
public Server(int port) {
this.port = port;
startServer();
}
public void startServer() {
try {
this.server = new ServerSocket(this.port);
System.out.println("Starting chat server at port " + this.port + "...");
while (true) {
Socket s = this.server.accept();
System.out.println("Client connected - " + s.getLocalAddress().getHostName());
Thread client = new Thread(new Client(s));
client.start();
}
} catch (IOException e) {
System.out.println("Error found!");
e.printStackTrace();
}
}
}
public class Client implements Runnable {
private Socket client;
public Client(Socket client) {
this.client = client;
}
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
System.out.println("Client says - " + read.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Should I open - close the connection each time my client GUI sends a message or open a connection one time and keep it open ?
Connection between a Client and Server is generally open for the entire session of messaging and not recreated for sending each message. So keep it open until the client or the Server has to go away.
Look at your Client thread that you start in your server upon accepting a Connection.
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
System.out.println("Client says - " + read.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
Does this give you a hint ? Well - you have to arrange for some sort of looping here within your run() - listening for more inputs from that client.
Just do some changes
Server side:
public void run() {
try {
BufferedReader read = new BufferedReader(new InputStreamReader(
this.client.getInputStream()));
while (true) {
System.out.println("Client says - " + read.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Client side:
use PrintWriter instead of BufferedWriter that provide print new line functionality and auto flush property.
this.write = new PrintWriter(new OutputStreamWriter(this.socket.getOutputStream()),
true);
....
public void actionPerformed(ActionEvent e) {
System.out.println(this.text.getText());
try {
writer.write(this.text.getText());
writer.println();
} catch (Exception e1) {
e1.printStackTrace();
}
}
I'm having a problem with a little game I'm designing in my class.
The problem is that I got two clients connected to a server. (client1 and client2) They are each running a game, which in the end, closes the window. As the game window is a JDialog, it will then, when it's closed, send a message, through a socket, to the server, telling it that it's done. I want the server to know which of the two clients were completed first. They are reporting through a PrintWriter on the sockets' OutputStream.
What I did was this:
in1 = new BufferedReader(new InputStreamReader(client.getInputStream()));
in2 = new BufferedReader(new InputStreamReader(client2.getInputStream()));
try {
in1.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
try {
in2.readLine();
} catch (IOException ex) {
Logger.getLogger(gameServer.class.getName()).log(Level.SEVERE, null, ex);
}
Problem is that it waits for the first input, before it even starts listening on the second. How can I make it listen on both at the same time? Or solve my problem some other way.
Thanks!
Server connection should work like this:
Server gameServer = new Server();
ServerSocket server;
try {
server = new ServerSocket(10100);
// .. server setting should be done here
} catch (IOException e) {
System.out.println("Could not start server!");
return ;
}
while (true) {
Socket client = null;
try {
client = server.accept();
gameServer.handleConnection(client);
} catch (IOException e) {
e.printStackTrace();
}
}
In hanleConnection() you start a new thread and run the communication for this client in the created thread. Then the server can accept a new connection (in the old thread).
public class Server {
private ExecutorService executor = Executors.newCachedThreadPool();
public void handleConnection(Socket client) throws IOException {
PlayerConnection newPlayer = new PlayerConnection(this, client);
this.executor.execute(newPlayer);
}
// add methods to handle requests from PlayerConnection
}
The PlayerConnection class:
public class PlayerConnection implements Runnable {
private Server parent;
private Socket socket;
private DataOutputStream out;
private DataInputStream in;
protected PlayerConnection(Server parent, Socket socket) throws IOException {
try {
socket.setSoTimeout(0);
socket.setKeepAlive(true);
} catch (SocketException e) {}
this.parent = parent;
this.socket = socket;
this.out = new DataOutputStream(socket.getOutputStream());;
this.in = new DataInputStream(socket.getInputStream());
}
#Override
public void run() {
while(!this.socket.isClosed()) {
try {
int nextEvent = this.in.readInt();
switch (nextEvent) {
// handle event and inform Server
}
} catch (IOException e) {}
}
try {
this.closeConnection();
} catch (IOException e) {}
}
}