Client Class
import java.io.PrintWriter;
import java.net.Socket;
public class Client
{
public static void main(String[] args)
{
try
{
System.out.println(" Starting Client ");
Socket socket = new Socket ("localhost",55555);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello from client");
printWriter.println("Conected, Yes!");
socket.close();// Changes as suggested by Jack
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server Class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
public static void main(String[] args)
{
System.out.println(" inside main ");
try
{
System.out.println("Starting Server");
ServerSocket serverSocket= new ServerSocket(55555);
Socket clientSocket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine= bufferedReader.readLine())!=null)
System.out.println("Server Message:"+inputLine);
}
catch (IOException e)
{
System.out.println("IOException "+e);
}
}
}
Output:
Starting Server
Server Message:Hello from client
Server Message:Conected, Yes!
IOException java.net.SocketException: Connection reset
Client and Server java files are in the same package.
What would trigger IOException in the following code?
Is it something to do with Eclipse?
FYI, I am using Eclipse SDK
Version: 4.2.2
Build id: M20130204-1200
The problem is that your client opens a Socket, sends some data and then exits the program, thus abruptly closing the connection.
You should call close() on the Socket from the client side to notify the server that the socket it is going to be closed.
As #Jack mentioned in his answer you need to close() your socket before the client application exit.
Socket is AutoCloseable
The safe way of work with closable resource is creation in try block:
public class Client {
public static void main(String[] args) {
System.out.println(" Starting Client ");
try(Socket socket = new Socket("localhost", 55555)) {
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("Hello from client");
printWriter.println("Conected, Yes!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
and it will be closed automatically on exit (from try section).
Related
I created a SOA service with Socket Adapter on JDeveloper and I need to run/test it using Java. So I created a server class and a client class but I am getting an error
I did some research on how to create this service and test it and I came across some helpful material online but yet I'm getting an error and I dont know how to fix it. I am very new to making socket servers and stuff.
here is my server class
package client;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
try {
ServerSocket socket = new ServerSocket(12110);
Socket s=socket.accept();
System.out.println("Connected!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and here is my client class
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class Client{
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12110);
OutputStream os = socket.getOutputStream();
os.write("FirstName,LastName\nWaslley,Souza\nJohn,Snow".getBytes());
os.flush();
socket.shutdownOutput();
BufferedReader soc_in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = soc_in.readLine();
System.out.println("Response: " + response);
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
here is the error I get:
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at client.Client.main(Client.java:23)
This happens because your server code exits after accepting a socket connection. Consequently, the JVM of this server will exit and (among others) close all socket connections it holds. This results in a SocketException on the client side.
To fix this, you should prevent the server's JVM from exiting, for instance by nesting the accept() call in a while loop:
public class Server {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(12110);
while (true) {
Socket s = socket.accept();
System.out.println("Connected! to " + s);
}
} catch (final Exception e) {
e.printStackTrace();
}
}
}
Server Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Class1 {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 12110;
public static void main(String args[]) throws IOException, ClassNotFoundException {
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while (true) {
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client " + message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if (message.equalsIgnoreCase("exit")) {
break;
}
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Client Code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
//establish socket connection to server
socket = new Socket(host.getHostName(), 12110);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
oos.writeObject("SEND SOME DATA");
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
do in this way.
yo #Mike sorry was not clear last time dig in this is the full server code
import java.net.ServerSocket;
import java.net.Socket;
import java.io.*;
public class Serv1 {
public static void main(String[] args) {
new Serv1().start();
}
public void start(){
String input = "";
try(ServerSocket socket = new ServerSocket(12110)) {
System.out.println("Connected!");
while (true) {
try(Socket server = socket.accept()){
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while ((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("Echoed: " + input);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
This should do it
String input= "";
Socket server=socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream(), "UTF-8"));
PrintStream echo = new PrintStream(server.getOutputStream());
while((input = in.readLine()) != null && !input.equals(".")) {
System.out.println(input);
echo.println("echo: "+input);
}
So there this problem that has been giving me headaches for days now.I am making a multi-user chat application.My design is as follows:
1.There is a login window.
2.As soon as the details are entered, the client-side chat window opens.
3.Now the user starts typing.
4.As soon as he hits enter or clicks on the send button,the message is sent to the server.
5.The server sends it to all clients, including the one that send it the original message.
The problem:I am unable to receive any messages from the server to the client.
Here is my server class:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class Server implements Runnable {
static InetAddress address;
static ArrayList<Integer> clients=new ArrayList<Integer>();
static ArrayList<Socket> socs=new ArrayList<>();
static String message="";
static DataOutputStream toClient;
static ServerSocket socket;
static Socket socketNew;
static boolean running=false;
public static void main(String[] args) throws IOException
{
socket=new ServerSocket(8000);
System.out.println("Server started on port 8000");
running=true;
while(true)
{
socketNew=socket.accept();
socs.add(socketNew);
address=socketNew.getInetAddress();
System.out.println("connected to client at address: "+address);
Server server=new Server();
new Thread(server).start();
}
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socketNew.getInputStream()));
String message;
PrintWriter out;
while ((message = br.readLine()) != null) {
System.out.println(message);
for (Socket s : socs) // sending the above msg. to all clients
{
out = new PrintWriter(s.getOutputStream(), true);
out.write(message);
out.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
And here is the receive_message function in the client class.Note that this method,I've run on a separate thread that starts as soon as the user logs-in.
public void receive_data()
{while(true)
{
try {
BufferedReader in;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(in.readLine()!=null)
{
System.out.println(in.readLine());
console(in.readLine());
}
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Any suggestions?Thanks for your time. :-)
You are writing messages without a line ending, while your client is waiting for a line ending character in the readLine loop. By placing out.write('\n') in your server send loop, it will also send a newline character.
Example:
for (Socket s : socs) {
out = new PrintWriter(s.getOutputStream(), true);
out.write(message);
out.write('\n'); // added this line
out.flush();
}
Here's my code:
SERVER:
package server;
public class Main {
public static void main(String args[]) {
new EchoServer(9000);
}
}
+
package server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private ServerSocket server;
public EchoServer(int port) {
try {
server = new ServerSocket(port);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(in.readLine() + " | MOD");
socket.close();
}
} catch(Exception err) {
err.printStackTrace();
}
}
}
CLIENT:
package client;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Main {
public static void main(String args[]) {
try {
while (true) {
Socket socket = new Socket("localhost", 9000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
out.println(input.readLine());
System.out.println(in.readLine());
socket.close();
}
} catch (Exception err) {
System.out.println(err);
}
}
}
It works all as it should, except that I want when the server sends the "message" + " | MOD" to the client, I want the server to send that to all clients, how can I do that?
I am new to Java, but not to coding so please help me if I've done some wrong stuff that can be done easier or better.
Please help.
Thanks alot.
What you can do is save the client sockets in an array, and then use a for loop to send to each socket.
First, declare your clientSocket array; note that 5 is just an arbitrary size used for testing. Also, declare a counter int.
public Socket clientSocket[] = new Socket[5];
public int intLastSocket = 0;
// this should be placed where you're waiting to accept connections
while (true) {
printTCP("Ready to accept welcome socket");
clientSocket[intLastSocket] = welcomeSocket.accept();
intLastSocket++;
}
// on the server, call this to send. s is a reference to the server object
public void sendToAllTCP(TCPServer s, String message) {
for (Socket z : s.clientSocket) {
if (z != null) {
PrintStream outToClient = null;
try {
outToClient = new PrintStream(z.getOutputStream());
outToClient.println(message);
} catch (IOException e) {
TCPServer.printTCP("Caught an IO exception trying "
+ "to send to TCP connections");
e.printStackTrace();
}
}
}
}
IN YOUR CODE:
package com.murplyx.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
private ServerSocket server;
// use the clientSocket Array to save each new connection
public Socket clientSocket[] = new Socket[5];
public EchoServer(int port) {
try {
server = new ServerSocket(port);
// this should be placed where you're waiting to accept connections
while (true) {
System.out.println("Ready to accept welcome socket");
clientSocket[intLastSocket] = server.accept();
intLastSocket++;
//send your message here, note that putting
//it here will send it each time u add a new connection
sendToAllTCP(/*the message you want to send */);
}
} catch(Exception err) {
err.printStackTrace();
}
}
public void sendToAllTCP(String message) {
// this is an enchanced for loop, i don't know if it's in other languages
// but in java it's supposed to let you loop through
//each object in any iterable list
// such as array, arraylist, linkedlist, etc
for (Socket z : clientSocket) {
if (z != null) {
//basically this chunk of code declares output and input streams
//for each socket in your array of saved sockets
PrintStream outToClient = null;
try {
outToClient = new PrintStream(z.getOutputStream());
outToClient.println(message);
} catch (IOException e) {
System.out.println("Caught an IO exception trying "
+ "to send to TCP connections");
e.printStackTrace();
}
}
}
}
}
Depending on when you want to send your message, you can use the console and sys.in to send it. For example, if you read a line from sys.in and it .equals("sendMsg"), then you can call sendToAllTCP(yourmessage)
You should take a look at multiThreaded chat Server. Each client wich connects gets it's own thread.
Here is the perfect answer to your question:
multithread client-server chat, using sockets
Good luck mate!
i am creating a LAN game that accepts strings and parses them from structured english and displays them on a grid. i have created the server and client and it works but im having some issues. when i send a string it doesnt appear on the other machine right away. for some reason the string is only sent to the other machine once the other machine sends something over. i dont know why this happens. Could you please help me find out why it doesnt send straight away. Thanks
Server Code:
import java.awt.Point;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class studentServer{
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();
public ServerPlayergameMain gm;
public static void main(String args[]) throws Exception{
}
public void run(String commandMessage){
while(true){
try{
printWriter.println(commandMessage+"\n");
String input = bufferedReader.readLine();//reads the input from textfield
console.readLine("Client message: "+input);//Append to TextArea
}catch(Exception e){}
}
}
public void serverStartActionPerformed() {
System.out.println("Server has started!");
try{
serverSocket = new ServerSocket (8888); // socket for the server
socket = serverSocket.accept(); // waiting for socket to accept client
JOptionPane.showMessageDialog(null, "Your opponent has connected!", "Opponent Connection!", JOptionPane.INFORMATION_MESSAGE);
gm = new ServerPlayergameMain();
gm.setVisible(true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads line from input streamer
printWriter = new PrintWriter(socket.getOutputStream(),true);
}catch(IOException | HeadlessException e){
System.out.println("Server not running!"); //print message if server is not running
}
}
}
Client Code:
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();
public ClientPlayergameMain gm;
public void Clients(String address) {
try{
socket=new Socket("localhost",8888);//Socket for client
//below line reads input from InputStreamReader
bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//below line writes output to OutPutStream
printWriter=new PrintWriter(socket.getOutputStream(),true);
JOptionPane.showMessageDialog(null, "Connected to server successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
gm = new ClientPlayergameMain();
gm.setVisible(true);
System.out.println("Connected");//debug code
}catch(Exception e){
JOptionPane.showMessageDialog(null, "No Connection to server", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println("Not Connected");
}
}
public static void run(String commandMessage){
while(true){
try{
printWriter.println(commandMessage+"\n");
String input = bufferedReader.readLine();
System.out.println("From server:" +input);
}catch(Exception e) {}
}
}
}
The code works but i dont know why there is a condition for the other machine to send something.
Thanks for your time.
A lot of compilation problems are there in you code. Some of the classes and objects are missing to resolve.
Still I have tried it to figure out the issue.
It may be the reasons:
sending new line character \n in printWriter.println(commandMessage+"\n"); statement, just remove \n.
client and server both are writing first in printWriter.println(commandMessage+"\n"); statement, make it last in anyone class
Here is the code:
StudentServer.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class StudentServer {
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
public static void main(String args[]) throws Exception {
StudentServer studentServer = new StudentServer();
studentServer.serverStartActionPerformed();
studentServer.run("server");
}
public void run(String commandMessage) {
if (true) {
try {
printWriter.println(commandMessage);
String input = bufferedReader.readLine();// reads the input from textfield
System.out.println("Client message: " + input);// Append to TextArea
} catch (Exception e) {
}
}
}
public void serverStartActionPerformed() {
System.out.println("Server has started!");
try {
serverSocket = new ServerSocket(8888); // socket for the server
socket = serverSocket.accept(); // waiting for socket to accept client
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads
// line
// from
// input
// streamer
printWriter = new PrintWriter(socket.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Server not running!"); // print message if server is not running
}
}
}
StudentClient.java:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
public void clients() {
try {
socket = new Socket("localhost", 8888);// Socket for client
// below line reads input from InputStreamReader
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// below line writes output to OutPutStream
printWriter = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Connected");// debug code
} catch (Exception e) {
System.out.println("Not Connected");
}
}
public void run(String commandMessage) {
if (true) {
try {
String input = bufferedReader.readLine();
System.out.println("From server:" + input);
printWriter.println(commandMessage);
} catch (Exception e) {
}
}
}
public static void main(String args[]) throws Exception {
StudentClient studentClient = new StudentClient();
studentClient.clients();
studentClient.run("client");
}
}
Have you tried printWriter.flush() after each write/print?
There are quite a few little problems, as Braj points out. The main one is in this sequence on your server side:
serverSocket = new ServerSocket (8888); // socket for the server
socket = serverSocket.accept(); // BLOCKS waiting for socket to accept client
// ..
printWriter = new PrintWriter(socket.getOutputStream(),true);
This means that printWriter, which you use to write to the client, doesn't even exist until after the server has listened for, blocked waiting on, and accepted a connection from the client.
If you want the connection to be opened for reading and writing without seeming to send anything from the client, send a handshake from the client. You could copy SMTP, and use HELO <myname>. That even tells the server who's calling.
Update after further reading:
I've always done like you have, and used the implicit connect that happens when you use getOutputStream() on the client side. However, Socket does allow you to connect an existing socket manually, using Socket#connect(). Try that, maybe it will work better than a handshake, for you.
Environment: Java 6, windows xp
I am trying to write a client-server TCP socket application. Need to detect on the server, when the client has closed the socket. All the information on the Internet, says that the server will throw a socket exception when its not able to write.
However, when I run the code (see below), I see that the server gets the exception only when the client doesn't read anything from the stream. When the client reads from the input stream, no exception is thrown on the server.
can someone please tell me the right way to detect a client side socket close (and also explain the behavior exhibited by the code below)?
Code:
package com.connection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
public class Test implements Runnable{
ServerSocket ss = null;
public Test() throws Exception{
ss = new ServerSocket(9999);
}
public void run(){
try{
Socket s = ss.accept();
Writer w = new OutputStreamWriter(s.getOutputStream());
w.write("Hello\n");
w.flush();
System.out.println("Server: wrote string 1");
System.out.println("Server: sleeping...");
Thread.sleep(5000);
System.out.println("Server: woke up");
w.write("Hello\n");
w.flush();
System.out.println("Server: wrote string 2");
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception{
Thread server = new Thread(new Test());
server.start();
Thread client = new Thread(new TestClient());
client.start();
}
}
class TestClient implements Runnable{
public void run() {
try {
Socket s = new Socket("localhost", 9999);
// Comment out the below 4 lines to see the write exception on server
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("Client: reading input...");
String str = r.readLine();
System.out.println(str);
// Comment the *above* 4 lines to see exception on server
Thread.sleep(1000);
System.out.println("Client: woke up");
s.close();
System.out.println("Client: socket closed");
}catch(Exception e){
e.printStackTrace();
}
}
}