I tried to find something similar to help me with my code and I also tried to do it by myself but I got stuck on the end and I would really appreciate if someone would help me with that.
So I have already working simple Java Client/Server code and what i want to do is to upgrade it so it can work both ways, right now after launching the server and connecting to it by the client everything what u write as a client will be shown on the server too and i want to upgrade it so what i write on the client will be shown on the server and what i write on the server will be shown on the client.
myServer.java
import java.io.*;
import java.net.*;
public class myServer {
public static void main (String[] args) {
try {
int i=0;
ServerSocket ss = new ServerSocket(9000);
System.out.println("Listening...");
Socket s = ss.accept();
System.out.println("Connection accepted");
InputStream d1 = s.getInputStream();
while ((char)i !='q')
{
i = d1.read();
System.out.print((char)i);
}
s.close();
ss.close();
} catch (Exception e) {System.out.println("Error"); }
}
}
myClient.java
import java.io.*;
import java.net.*;
public class myClient {
public static void main(String[] args) {
try {
int i=0;
Socket s=new Socket("localhost",9000);
OutputStream o = s.getOutputStream();
while ((char)i !='q')
{
i = System.in.read();
o.write((char)i);
}
s.close();
} catch(Exception e) {System.out.println("Error"); }
}
}
Thank You in advance.
Related
I am complete beginner and i have assignment to send something to server and get it back while using threads too.
My problem is that no matter which port I use, I get connection refused.
I think it might something to do with threads, but I am unsure what to do with them as it seems both start properly and client is the one throwing exception. I read somewhere that server should have some time to start connection so I put sleep but same thing again.
Main:
package advancedjavaassignment1;
public class MAIN {
public static void main(String[] args) {
SERVER.mainServer();
CLIENT.mainClient();
}
}
SERVER:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class SERVER {
static void mainServer() {
serverTHREAD serverThread = new serverTHREAD();
serverThread.start();
try (
ServerSocket calcServer = new ServerSocket(10001); //Server created on port 2390
Socket inSocket = calcServer.accept(); //Server is listening
DataInputStream FromClient = new DataInputStream(inSocket.getInputStream());
DataOutputStream ToClient = new DataOutputStream(inSocket.getOutputStream());) {
int a = FromClient.readInt();
ToClient.writeInt(a);
}
catch (IOException e) {
System.out.println(e.getMessage()+ "Server");
}
}
}
}
CLIENT:
package advancedjavaassignment1;
import java.net.*;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
public class CLIENT {
static void mainClient() {
serverTHREAD clientThread = new serverTHREAD();
clientThread.start();
try {Thread.sleep(2000); System.out.println("break");} catch (InterruptedException ex) { }
try (Socket ClientSocket = new Socket("localhost",80);
DataInputStream FromServer = new DataInputStream(ClientSocket.getInputStream());
DataOutputStream ToServer = new DataOutputStream(ClientSocket.getOutputStream());) {
ToServer.writeInt(10);
int sum = FromServer.readInt();
System.out.println(sum);
ClientSocket.close();
}
catch(IOException exception)
{
System.out.println(exception.getMessage() + " - Client");
}
}
}
Looks like your server runs on port 10001 (although you wrote 2390 in the comment) and the client tries to connect to port 80. The client finds no server listening on that port, hence the connection refused error.
My apology, I forgot to change it, as I was experimenting with everything, this does not work even when ports are same.
I solved this by implementing Runnable. Worked immediately.
I tried to connect two machines using Socket.
I put client code in Machine A:
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try {
Socket s = new Socket("IP ADDRESS",5555);
// Socket s = new Socket("localhost",6669);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Run the server code in Machine B
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(5555);
Socket s = ss.accept(); //establishes connection
DataInputStream dis = new DataInputStream(s.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ss.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
Both in machine in same network
But its not running and no error also coming in CMD.
First of all, when I compile the code using "localhost" as the hostname, and run the client and server apps on the same machine ... it works. The server receives the message and prints it.
From this, I conclude that the code is correct (enough) and the real problem is something to do with your networking; e.g.
It might be a routing problem.
It might be a firewall problem.
There might be something wrong with your physical network or network interfaces.
However none of these are programming problems.
my name is Jędrzej and I am new here. I was trying to write a simple chat in java. I am trying to make multithread server so multiple clients can connect to this server. My client works fine, but if I run two clients, they dont see each others responses. Code bellow:`
package serverthread;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerWIthThreads {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(1234);
while(true){
Socket socket = serverSocket.accept();
Runnable r = new ThreadForServer(socket);
Thread t = new Thread(r);
t.start();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
package serverthread;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ThreadForServer implements Runnable{
private Socket socket;
private ObjectInputStream inputStream;
private ObjectOutputStream outputStream;
public ThreadForServer(Socket i){
socket = i;
}
#Override
public void run(){
try{
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
outputStream.flush();
while(true){
String message = (String) inputStream.readObject();
outputStream.writeObject(message);
outputStream.flush();
}
}catch(IOException e){
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
`
The way you've implemented this, you're reading a message from one client and then writing it back to the same client.
You'll need to revise your program so that you can write the message to the Socket of the other connected client.
I am new in socket programming.
i have two java programs( Client.java and Server.java), For socket programming i want to compile my server.java code to server which always listen to socket, But i don't know what i do on server.
Server.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) {
String data = "Toobie ornaught toobie";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close();
skt.close();
srvr.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Client.java
import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
}
}
Search on how to compile Java files. In your case it will be javac Server.java to compile it, and then java Server to run. The same goes for Client.
Got it here.
http://www.careerbless.com/samplecodes/java/beginners/socket/SocketBasic1.php
Here server always listen to client.
Thank you guys for help.
I wrote a small client server program in Java. Server creates a ServerSocket on some port and keeps listening to it. Client sends some sample info to this server.
When I run Client the first time connection is accepted by server and info is printed by server. Then Client program exits. When I run Client again, connection is accepted however, data is not printed.
Please check following code.
Server Program
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(dis.available() > 0) {
System.out.println(dis.readByte());
}
}
}
}
Client Program
package javadaemon;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
} catch(IOException e) {
}
}
}
Please help me in finding why next time no data is received by server.
The reason is before server side receive data, the Client already exits, I just debug it. (Can't explain whey it works at the first time.)
Just change your code like the below, and it works.
package javadaemon;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class MyDaemon {
public static void main(String [] args) throws IOException {
ServerSocket ss = new ServerSocket(9879);
ss.setSoTimeout(0);
while(true) {
Socket s = ss.accept();
System.out.println("socket is connected? "+s.isConnected());
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println("Input stream has "+dis.available()+" bytes available");
while(true) {
try {
System.out.println(dis.readByte());
} catch (Exception e) {
break;
}
}
}
}
}
The Client must add flush before exits,
package javadaemon;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String [] args) {
try {
System.out.println("Connecting to " + "127.0.0.1"
+ " on port " + 9879);
Socket client = new Socket("127.0.0.1", 9879);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
for(int i=0; i<100; i++ ) {
out.writeUTF("Syn "+i);
}
out.flush();
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Place this in your Client program after for loop:
out.flush();
out.close();
client.close();
You need to flush your stream in order to push the data forward and clean the stream. Also, you will need to close your client socket.
I just tested this successfully.