I am trying to do a basic networking program using sockets
Server:
import java.io.*;
import java.net.*;
class Socketserver{
public static void main(String[]z)throws IOException{
System.out.println("Server is started");
ServerSocket ss=new ServerSocket(9999);
System.out.println("Waiting for client request");
Socket s=ss.accept();
System.out.println("client connected");
InputStreamReader a=new InputStreamReader(s.getInputStream());
BufferedReader b=new BufferedReader(a);
String str=b.readLine();
System.out.println("Client data"+str);
String nickname=str.substring(0,3);
OutputStreamWriter os=new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(os);
out.write(str);
os.flush();
System.out.println("data sent from server to client");
}}
Client
import java.io.*;
import java.net.*;
class Socketclient{
public static void main(String[]z)throws IOException{
String ip="localhost";// for same machine
int port=9999;
Socket s=new Socket(ip,port);
String str="Rujhaan";
OutputStreamWriter os=new OutputStreamWriter(s.getOutputStream());
PrintWriter out=new PrintWriter(os);
out.write(str);
os.flush();
InputStreamReader a=new InputStreamReader(s.getInputStream());
BufferedReader b=new BufferedReader(a);
String nickname=b.readLine();
System.out.println("data from server"+nickname);
}
}
The program compiles and there is no problem on the server but running client always gives connection refused or connection timed out exception.
I have tried different port names and also there is nor firewall problem.
Please suggest me what to do....
Problem is the function readLine. The Specification says the method read the stream until an new line ("\n") is received
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()
Change your input string to
String str="Rujhaan\n";
will works or alternative close the OutputStream on client to terminate data transmission.
out.close();
Related
I have made 2 classes, one is client.java and one is server.java. I am using socket to communicate between them. The server and client connects but don't send data and stays connected.
client.java:
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 42069);
System.out.println("Connected to the server!");
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream()));
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream()));
out.write("hi from client");
System.out.println(in.readLine());
s.close();
}
server.java:
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(42069);
System.out.println("\nWaiting For Connection...");
Socket s = ss.accept();
System.out.println("\nConnected to the client!");
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter
(newOutputStreamWriter(s.getOutputStream()));
System.out.println(in.readLine());
out.write("hi from server");
}
when both connect, they stay like this:
s.jaerverva
Waiting For Connection...
Connected to the client!
client.java
Connected to the server!
when i terminate the client, i get this error on the server:
Exception in thread "main" java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:966)
at java.base/sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:270)
at java.base/sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:313)
at java.base/sun.nio.cs.StreamDecoder.read(StreamDecoder.java:188)
at java.base/java.io.InputStreamReader.read(InputStreamReader.java:177)
at java.base/java.io.BufferedReader.fill(BufferedReader.java:162)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:329)
at java.base/java.io.BufferedReader.readLine(BufferedReader.java:396)
at HTTP.server.main(server.java:14)
I want my client to send a message to the server and the server send back the message received
but there is an issue with my client because It never reach the close() statement because of readLine()
therefore it just hangs there, what can I do to make it work ?
Server :
import java.net.*;
import java.io.*;
public class Server{
public static void main(String[] args){
try{
ServerSocket server=new ServerSocket(3535);
while(true){
Socket socket=server.accept();
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
String message=in.readLine();
System.out.println(message);
out.print(message);
out.flush();
in.close();
out.close();
socket.close();
} }
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
}
Client :
import java.net.*;
import java.io.*;
public class Client{
public static void main(String[] args){
try{
BufferedReader user_in =new BufferedReader(new InputStreamReader(System.in));
while(true){
Socket socket=new Socket("localhost",3535);
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
out.print(user_in.readLine());
out.flush();
String message_from_server = in.readLine();
System.out.println("Message from server : " + message_from_server);
out.close();
in.close();
socket.close();
}
}
catch(Exception e){
System.out.println(e);
e.printStackTrace();
}
}
}
The "problem" lies in readLine() in the server.
This is wanted behavior. BufferedReader implements readLine() in a way so that it blocks until it receives either one of: '\n', '\r', carriage return followed by a line feed, or an EOF
The client is sending neither of them.
Instead of using the print() method of PrintWriter, you could use println().
I am trying to make a java program for client-server communication
I need to initialize a server socket and a client socket.
The server socket will accept a connection from the client.
After the connection has been accepted, the input i give to the client will be submitted to the server which will tell the client if the communication was successfull or not.
This is my code :
import java.io.*;
import java.net.*;
public class ClientServer {
public static void main(Strings args[]) throws Exceptions{
/*initialize server socket*/
Socket client_socket = new Socket("localhost", 12345);
BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
String serverMsg = null;
while ((serverMsg = reader.readLine()) != null) {
System.out.println("Client: " + serverMsg);
ServerSocket server_socket;
server_socket=new ServerSocket(12345);
while (true) {
Socket mysocket=server_socket.accept();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
writer.write("prova\n");
System.out.printls("data sent");
}
}
}
but I need to get input from keyboard, not "from the code".
Thanks a lot.
For its partner app I switched the Client and Server code and the ports. Ran both these codes in two separate terminals. They were able to connect with each other but I was not able send message from one terminal to the other.
import java.net.*;
import java.io.*;
import java.util.Scanner;
class ChatHead1
{
public static void main()throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Client
Socket sock = new Socket("127.0.0.1", 2000);
OutputStream ostream = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(ostream);
System.out.print("\nYou:");
String message1 = br.readLine(); //Inputting Message For Sending
dos.writeBytes(message1);
//Server
ServerSocket sersock = new ServerSocket(5000);
System.out.print("\nThem: ");
Socket sockServ = sersock.accept();
InputStream istream = sockServ.getInputStream();
DataInputStream dstream = new DataInputStream(istream);
String message2 = dstream.readLine();
System.out.println(message2); //Printing Received Message
//Client Close
dos.close();
ostream.close();
sock.close();
//Server Close
dstream .close();
istream.close();
sockServ.close();
sersock.close();
}
}
I would suggest that you should only use one Server/Client, because its a two way connection.
I dont really see why you are using a Client and a Server.
Try dos.flush(); after dos.writeBytes(message1);
I hava a problem with my code. I make a server with Java which waits for connections. When a client connects, if we(the server) send the command "showinfo", the cliend send its IP address back to the server.
The problem is that it is a multi-threaded server and many clients connect. So, if, for example, 2 clients connect to the server we have to type 2 times showinfo and then the clients give us the information. How can I make the clients respond immediately with typing "showinfo" for each one and don't wait until I type showinfo for all the clients. It's a bit tiring to type 50 times showinfo if there are 50 clients before you can execute your command. Thank you in advance (i have tried some thread synchronization and some sleep() join() commands but I haven't reach a conclusion yet I hope you can help a bit.)
Here 's the server code
import java.io.*;
import java.net.*;
import java.security.*;
public class Server implements Runnable{
private Socket server;
private static String command,info,message;
BufferedReader infromclient =null;
InputStream infromclient2=null;
DataOutputStream outtoclient =null;
static BufferedReader infrommaster=null;
private static int port=6789;
Server( Socket server ){
try{
this.server=server;
infromclient =new BufferedReader(new InputStreamReader(server.getInputStream()));
outtoclient =new DataOutputStream(server.getOutputStream());
infrommaster=new BufferedReader(new InputStreamReader(System.in));
}catch( IOException e ){
System.out.println("Exception accessing socket streams: "+e);
}
}
// main()
// Listen for incoming connections and handle them
public static void main(String[] args) {
ThreadGroup clients = new ThreadGroup("clients");
System.out.print("Waiting for connections on port " + port + "...");
System.out.println("\nIn total there are:"+clients.activeCount()+" clients\n");
try{
ServerSocket server = new ServerSocket(port);
Socket nextsocket;
// waiting for connections
while(true){
nextsocket = server.accept();
Thread client= new Thread(clients,new Server(nextsocket),"client"+(clients.activeCount()+1));
System.out.println("Client connected");
System.out.println("There are "+clients.activeCount()+" clients connected");
client.start();
}
}catch (IOException ioe){
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
public void run (){
try{
command=infrommaster.readLine();
outtoclient.writeBytes(command+"\n");
// showinfo
if(command.equals("showinfo")){
info=infromclient.readLine();
System.out.println("\nClient information\n\n" +info+"\n");
}
server.close();
}catch (IOException ioe){
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
and here is the code for the client:
import java.io.*;
import java.net.*;
import java.lang.*;
public class Client{
public static void main(String args[]) throws Exception{
String command2;
String info;
Socket clientSocket=null;
Socket scket=null;
BufferedReader inFromUser=null;
DataOutputStream outToServer=null;
BufferedReader inFromServer=null;
BufferedWriter tosite=null;
try{
clientSocket = new Socket(InetAddress.getLocalHost().getHostName(), 6789);
inFromUser =new BufferedReader(new InputStreamReader(System.in));
outToServer =new DataOutputStream(clientSocket.getOutputStream());
inFromServer =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}catch(UnknownHostException | IOException e ){
System.out.println("Problem "+e);
}
command2=inFromServer.readLine();
System.out.println("From Server:" +command2);
// showinfo
if (command2.equals("showinfo")){
try{
InetAddress myip=InetAddress.getLocalHost();
info =("IP: " +myip.getHostAddress()+"\n");
System.out.println("\nSome system information\n" + info);
outToServer.writeBytes(info);
}catch (Exception e){
System.out.println("Exception caught ="+e.getMessage());
}
}
outToServer.flush();
outToServer.close();
inFromUser.close();
inFromServer.close();
clientSocket.close();
}
}
** the command clientSocket = new Socket(InetAddress.getLocalHost().getHostName(), 6789); means that it tests my pc(my ip in port 6789) .
If one thread is blocking on the readline, the other should eventually get control. That's the whole point of multithreading. I think I know your problem. Move the code where you are reading the input command into the run() method of the server instead. Then you should be good. I think the problem is that your threads are starting after you are polling for input.
Move these lines from the Server constructor to Server's run() method:
infromclient =new BufferedReader(new InputStreamReader(server.getInputStream()));
outtoclient =new DataOutputStream(server.getOutputStream());
infrommaster=new BufferedReader(new InputStreamReader(System.in));