When ever I run the client after running the server, the server crashes with the error connection reset... here is my code:
initiate a client socket and connect to the server. wait for an input.
Client:
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String fromServer,fromUser;
public ClientTest() {
try {
socket = new Socket("127.0.0.1", 25565);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void start() {
try {
while ((fromServer = in.readLine()) != null) {
System.out.println(fromServer);
out.println("1");
}
System.out.println("CLOSING");
out.close();
in.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new ClientTest();
}
initiate a server socket and send a "2" to client and initiate a conversation
Server:
public ServerTest() {
try {
serverSocket = new ServerSocket(25565);
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
start();
}
public void start() {
try {
PrintWriter out;
out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in;
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// initiate conversation with client
out.println("2");
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.println("2");
}
System.out.println("Stopping");
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new ServerTest();
}
when ever I run the server everything is fine but when I run the client after that the server crashes with connection reset error.
ClientTest() does not call the start() method. Your client exits immediately after establishing the connection.
Alex's answer is right.
This program also goes to infinite loop. You need to add an exit condition in the while loop of client and server.
Related
I want to have a Server that is running and receives messages from Clients such as another Java Applications. I am doing this via BufferedReader with an InputStream and as long as i do it a single time it works as expected. The message gets processed by the method and writes the Test Message of the received message on the screen, but if i let it run in a while loop it says -
java.net.SocketException: Connection reset
So once the Server got a message i dont know how to get a second one, or any following one.
My main source code is:
public static void main (String[] args) {
int port = 13337;
BufferedReader msgFromClient = null;
PrintWriter msgToClient = null;
timeDate td = new timeDate(); //Class i did for myself to get time/date
ServerSocket s_socket = null;
try {
s_socket = new ServerSocket(port);
System.out.println("Server startet at "+td.getCurrDate()+" "+td.getCurrTime());
}
catch (IOException ioe) {
System.out.println("Server on Port "+port+" couldnt be created. \nException: "+ioe.getMessage());
}
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
msgFromClient = utils.createInputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Input Stream failed.\n Exception - "+ioe);
}
try {
msgToClient = utils.createOutputStream(socket);
} catch (IOException ioe) {
System.out.println("Creation of an Output Stream failed.\n Exception - "+ioe);
}
String input = null;
while (true) {
try {
input = msgFromClient.readLine();
} catch (IOException ioe) {
System.out.println(ioe);
}
if(input!=null) {
System.out.println("Jumping out of loop: "+input);
utils.processCode(input);
}
}
The both classes to create the streams look like this:
public static BufferedReader createInputStream (Socket socket) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
return br;
}
public static PrintWriter createOutputStream (Socket socket) throws IOException {
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
return pw;
}
The "processCode" class then simply is a switch.
Socket socket = null;
try {
socket = s_socket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You only accept one Connection an after this you are doing your handling. You need to open an new Thread for every connection
ExecutorService threadLimit = Executors.newFixedThreadPool(10);
while(true) {
Socket s = serverSocket.accept();
treadLimit.submit(new HandleThread(s));
}
I have created a chat server which is multi threaded and as and when the clients connect it initiates a separate thread for them to communicate. The problem is the my server is not broadcasting messages received from one client to all the other clients connected and I simply do not know how to implement it.
Following is my code, feel free to edit:
The serverclass:
ArrayList<ServerThread> clientlist = new ArrayList();
Hashtable clientList = new Hashtable();
private static ArrayList<PrintWriter> writers = new ArrayList<PrintWriter>();
public ChatServer(JTextField jtfA, JTextField jtfB, JTextArea jtaA, JTextArea tapane3) {
// TODO Auto-generated constructor stub
address= jtfA;
GETPORT=jtfB;
PORT=Integer.parseInt(jtfB.getText());
displaytext=jtaA;
clientside=tapane3;
}
public void run() {
// TODO Auto-generated method stub
try {
InetAddress ad=InetAddress.getLocalHost();
String ip=ad.toString();
address.setText(string);
address.setEditable(false);
System.out.println("Server IP is: " + ad);
ss = new ServerSocket (PORT);
Socket cs = null;
while (true)
{
cs=ss.accept();
System.out.println("Connected"+clientlist);
ServerThread handler = new ServerThread(cs,displaytext,clientside,writers);
clientlist.add(handler);
handler.start();
System.out.println(writers);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("DisConnect"))
{
try {
ss.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
The server thread class::
public class ServerThread extends Thread {
Socket client;
JTextArea display;
JTextArea clients;
ServerSocket server;
ArrayList<PrintWriter> writers ;
public ServerThread(Socket cs, JTextArea displaytext, JTextArea clientside, ArrayList<PrintWriter> writers) {
// TODO Auto-generated constructor stub
client=cs;
display=displaytext;
clients=clientside;
this. writers=writers;
}
public void run () {
try{
BufferedReader br = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
PrintWriter pr = new PrintWriter(
new OutputStreamWriter(
client.getOutputStream()));
String clientMsg="";
boolean all;
do {
//read msg from client
clientMsg = br.readLine();
//display.setText(clientMsg);
System.out.println("Server Received: " + clientMsg);
pr.println(clientMsg);
display.append(clientMsg+"\n");
clients.append(clientMsg+"\n");
pr.flush();
} while((all=br.readLine() != null));
br.close();
pr.close();
while (true) {
String input = br.readLine();
if (input == null) {
return;
}
for (PrintWriter writer : writers) {
writer.println("MESSAGE " + ": " + input);
}
}}
catch (UnknownHostException uhe){
System.out.println("Server issue");
}
catch (IOException ioe){
System.out.println("Server Error IO");
}
catch (Exception e){
System.out.println("Server Error General");
}}
}
Faulty do/while loop. You're throwing away every second line, and not detecting end of stream correctly. It should be:
while ((line = br.readLine()) != null)
I am trying to make some sort of login system, but the server and client wont talk to each other. I am not quite sure why they wont talk to each other, but any help is appreciated.
P.S The port is correctly set up on my router.
Client
public class Clients implements Runnable
{
String ip = "localhost";
int port = 25565;
Socket client;
static Thread thread;
boolean setup = false;
BufferedReader br;
PrintWriter pw;
public static void main(String[] args)
{
thread = new Thread(new Clients());
thread.start();
}
public void run()
{
while(!setup)
{
try {
client = new Socket(ip,port);
setup = true;
} catch (IOException e) {
setup = false;
}
}
try {
br = new BufferedReader(new InputStreamReader(client.getInputStream()));
pw = new PrintWriter(client.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.flush();
pw.write("client");
while(true);
}
}
Server
public class Server implements Runnable
{
int port = 25565;
String input;
ServerSocket server;
Socket clients;
BufferedReader br;
PrintWriter pw;
boolean setup = false;
static Thread thread;
public static void main(String[] args)
{
thread = new Thread(new Server());
thread.start();
}
public void run()
{
try {
server = new ServerSocket(port);
clients = server.accept();
br = new BufferedReader(new InputStreamReader(clients.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("getting input");
while((input = br.readLine()) != null)
{
System.out.println(input);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You should first do write and then flush
pw.write("client\n");
pw.flush();
Also place \n in the line that you are writing since in the client you are doing br.readline(). So it will wait till a new line is available.
I see two problems. The first is that pw.flush should be invoked after pw.write. The second is that the server is waiting on readLine(), which will only return when it encounters a line ending. You should change Clients to invoke pw.write("clients\n"), adding the newline.
I have a Java Server and one(or more) Android Clients. For now I want them to communicate simply with strings. When i write from android I can get the data in Java Server, but when I try to get the answer from server the Android application stop working. The codes is reported below:
Java Server:
public class Server {
private static int port=12346, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
String end = server.getInetAddress().toString();
System.out.println("\n"+end+"\n");
doComms conn_c= new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
public doComms(Socket server) {
this.server=server;
}
#SuppressWarnings("deprecation")
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(server.getOutputStream())),
true);
while((line = in.readLine()) != null && !line.equals(".")) {
input=input + line;
}
JOptionPane.showMessageDialog(null, input);
out.println("Enviado");
server.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
And Android client's code (it's called every time a button is pressed inside onClick method):
public String enviaMensagem(){
String resposta="";
new Thread(new ClientThread()).start();
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(ip, port);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(input.getText().toString());
resposta = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return resposta;
}
You are using an unsorted mixture of readUTF(), writeUTF(), readLine(), etc. They're not all interoperable. Settle on one of them. If you use writeUTF() you must use readUTF() at the other end. If you use readLine() you must write lines at the other end, with a line terminator such as \r\n or \n.
I'm creating an update client via Sockets and I'm getting a Broken Pipe on the server side. The server accepts a client socket and responds to the same socket with either a message or a large byte array (~180MB). The error does not happen when testing locally (both client and server on the same machine) and it seems that it happens while sending the byte array. I'm not specifying a time out on the client socket and don't know why it is closing before reading the full response. Its my first time working with sockets and any help would be appreciated.
My Client Socket Code:
public static Response makeRequest(Request req) throws IOException {
Response response = null;
Socket echoSocket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
echoSocket = new Socket(serverHost, 10008);
out = new ObjectOutputStream(echoSocket.getOutputStream());
in = new ObjectInputStream(
echoSocket.getInputStream());
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.writeObject(req);
try {
response = (Response)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
return response;
}
Response is just a POJO holding the response (string/byte[] and other data)
My Server Code (copied an example of Sun/Oracle site and added my code to it)
public class Server extends Thread {
private Socket clientSocket;
public Server(Socket clientSocket) {
this.clientSocket = clientSocket;
start();
}
public void run()
{
{
System.out.println ("New Communication Thread Started");
try {
ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
Request request = null;
try {
request = (Request)in.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
UpdateDAO dao = new UpdateDAO();
ClientDAO cdao = new ClientDAO();
Update update = null;
Client client = null;
Session s = HibernateUtil.currentSession();
Transaction t = s.beginTransaction();
if (request != null) {
client = cdao.getClient(request.getClientId());
LogItem log = new LogItem();
log.setClient(client);
log.setTimestamp(new Date());
log.setAction(request.getAction());
if (request.getResponse() != null) {
update = dao.getUpdate(request.getResponse().getUpdateId());
}
TaskContext ctx = new TaskContext(request, client, update, log);
System.out.println("Action: " + request.getAction().getDescription());
Task task = TaskFactory.getTask(request.getAction());
System.out.println(task.getClass().getName());
Response response = task.perform(ctx);
out.writeObject(response);
log.setClientTaskDescription(request.getMessage());
log.setUpdate(ctx.getUpdate());
dao.save(ctx.getLog());
if (ctx.getUpdate() != null) {
dao.update(ctx.getUpdate());
}
} else {
out.writeObject(new Response("what"));
}
t.commit();
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
}
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(10008);
System.out.println ("Connection Socket Created");
try {
while (true)
{
System.out.println ("Waiting for Connection");
new Server (serverSocket.accept());
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: 10008.");
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
}
If the client is, in fact, running out of memory:
java -Xmx512m -jar <the jar>
or
java -Xmx512m com.foo.blah.YourClass
would increase the maximum heap for the client/server. Keep in mind you may have to increase the heap for both sides of the pipe since both sides would be reading all ~180mb into memory at runtime.