close Client

how to close client to dont get java.net.SocketException: Connection reseti dont know why Telnet conection is okI know that i close socket i wrong order but how to do this properly
[215 byte] By [argola] at [2007-11-27 6:15:52]
# 1

The correct way to close a connection is to close the output stream of the socket. If you've wrapped output streams or Writers around it you need to close the last one of these you wrapped instead. This ensures that any final flushing required takes place. Once you've done that you don't need to close its input stream or the socket itself as they are both already closed.

ejpa at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 2

Now i get the same exceprion in client

When i click exit button i close streams ,I try to stop or destroy thread but

the same result

CLIENT LOOP

*

*

*

if(e.getActionCommand().equals("exit")){

try {

petla = false;

out.close();

in.close();

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

*

*

*

public void run() {

while(petla){

try {

in = new DataInputStream( gniazdo.getInputStream());

out = new DataOutputStream( gniazdo.getOutputStream());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

pole.append("SERWER DEAD");

break;

}

}

}

SERWER LOOP

public void run() {

GUI.pole.append("START"+Thread.currentThread().getName()+"\n");

while (true) {

GUI.pole.append("WAIT"+Thread.currentThread().getName());

try {

s = theServer.accept();

DataOutputStream out = new DataOutputStream(s.getOutputStream());

DataInputStream in = new DataInputStream(s.getInputStream());

while (true) {

int n = in.read(ss);

if (n == -1)

{

GUI.pole.append("END connection for THREAD "+Thread.currentThread().getName()+"\n");

break;

}

tmp="\n\r"+"kod: " + (int)n + " binarnie:"+Integer.toBinaryString(n)+"\n\r";

out.write(tmp.getBytes());

//out.write(n);

out.flush();

} // end while

} // end try

catch (IOException ex) {

}

} // end while

} // end run

argola at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 3
That's not your complete client code. Where does it write and read all that stuff that the server is reading and writing?
ejpa at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 4

CLIENT

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

import javax.swing.*;

public class Klient2 extends JFrame implements Runnable,ActionListener,WindowListener{

JTextField wyss;

JScrollPane scrollPane2;

JList listaUSER;

JLabel l1;

Socket gniazdo;

Thread w;

DataInputStream in;

DataOutputStream out;

Convert convert = new Convert();

JButton b1,b2,b3;

String login;

byte [] buffor = new byte [200];

boolean l = true,petla = true;

public Klient2(){

this.addWindowListener(this);

this.setLayout(null);

this.setSize(500,400);

wyss = new JTextField();

wyss.setSize(160,30);

wyss.setLocation(80,140);

this.add(wyss);

b1 = new JButton("Wyslij");

b1.setBounds(220,250,80,30);

b1.addActionListener(this);

b1.setActionCommand("wyslij");

b1.setVisible(false);

this.add(b1);

b2 = new JButton("login");

b2.setBounds(250,140,80,30);

b2.addActionListener(this);

b2.setActionCommand("login");

this.add(b2);

l1 = new JLabel();

l1.setBounds(180,220,100,30);

this.add(l1);

b3 = new JButton("exit");

b3.setBounds(220,300,80,30);

b3.addActionListener(this);

b3.setActionCommand("exit");

b3.setVisible(false);

this.add(b3);

listaUSER = new JList();

//listaUSER.addMouseListener(this);

scrollPane2 = new JScrollPane(listaUSER,

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

scrollPane2.setSize(120,200);

scrollPane2.setLocation(240, 20);

scrollPane2.setVisible(false);

this.add(scrollPane2);

}

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("exit")){

try {

petla = false;

//gniazdo.close();

out.close();

in.close();

l = true;

System.exit(0);

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

if(e.getActionCommand().equals("login")){

if(l == true){

try {

gniazdo = new Socket("127.0.0.1",2347);

} catch (UnknownHostException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

}

w = new Thread(this);

w.start();

l = false;

try {

out = new DataOutputStream( gniazdo.getOutputStream());

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

String header = "L1";

String text = wyss.getText();

byte [] headerByte = header.getBytes();

byte [] loginByte = text.getBytes();

int loginSize = loginByte.length;

byte [] loginSizeByte =convert.int2bytearray(loginSize);

byte [] sendLogin = new byte [2+4+loginSize];

for(int i=0;i<2;i++){

sendLogin[i] = headerByte[i];

}

for(int i=2,j=0;i<6;i++,j++){

sendLogin[i] = loginSizeByte[j];

}

for(int i=6,j=0;i<sendLogin.length;i++,j++){

sendLogin[i] = loginByte[j];

}

try {

out.write(sendLogin);

out.flush();

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

public void run() {

while(petla){

try {

in = new DataInputStream( gniazdo.getInputStream());

out = new DataOutputStream( gniazdo.getOutputStream());

in.read(buffor);

byte [] headerByte = new byte [2];

for(int i=0;i<2;i++){

headerByte[i] = buffor[i];

}

String hader = new String(headerByte);

System.out.println(hader);

if(hader.equals("LO")){

scrollPane2.setVisible(true);

wyss.setVisible(false);

b2.setVisible(false);

b3.setVisible(true);

l1.setText("");

byte [] listaSizeByte = new byte [4];

for(int i=2,j=0;i<6;i++,j++){

listaSizeByte[j] = buffor[i];

}

int listaSize = convert.bytearray2int(listaSizeByte);

System.out.println(listaSize);

byte [] listaByte = new byte [listaSize ];

for(int i=6, j=0 ; i < 6 + listaByte.length ; i++ ,j++){

listaByte[j] = buffor[i];

}

String listaIN = new String(listaByte);

System.out.println(listaIN);

String lis [] = listaIN.split("#");

listaUSER.setListData(lis);

}else if(hader.equals("LN")){

l1.setText("login zajety");

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

break;

}

}

}

public void windowOpened(WindowEvent arg0) {

// TODO Auto-generated method stub

}

public void windowClosing(WindowEvent e) {

System.out.println("ZAMYKAM");

try {

petla = false;

if(l == false){

out.close();

in.close();

}

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

public void windowClosed(WindowEvent arg0) {

}

public void windowIconified(WindowEvent arg0) {

// TODO Auto-generated method stub

}

public void windowDeiconified(WindowEvent arg0) {

// TODO Auto-generated method stub

}

public void windowActivated(WindowEvent arg0) {

// TODO Auto-generated method stub

}

public void windowDeactivated(WindowEvent arg0) {

// TODO Auto-generated method stub

}

public static void main(String[] args) {

Klient2 frmae = new Klient2();

frmae.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frmae.setSize(400,400);

frmae.setLocation(10,10);

frmae.setVisible(true);

}

}

SERVER

-

import java.net.*;

import java.util.ArrayList;

import java.util.HashMap;

import java.io.*;

public class Serwer2 extends Thread {

public final static int defaultPort = 2347;

ServerSocket theServer;

Socket s;

static int numberOfThreads = 2;

String headerOUT,listOUT="",loginString ;

byte [] buffor = new byte [200];

byte [] outByte;

byte [] headerByte = new byte[2];

byte [] loginSize = new byte[4];

serwerGUI2 GUI;

Convert convert = new Convert();

ArrayList userList = new ArrayList();

ArrayList socketList = new ArrayList();

HashMap mapa = new HashMap();

public Serwer2(serwerGUI2 gui,ServerSocket ss,ArrayList l ,ArrayList ll,HashMap lll ){

this.GUI =gui;

this.theServer = ss;

this.userList = l;

this.socketList =ll;

this.mapa =lll;

}

public void run() {

GUI.pole.append("Uruchomiono watek nasluchujacy"+Thread.currentThread().getName()+"\n");

while (true) {

GUI.pole.append("Watek "+Thread.currentThread().getName()+"oczekuje polaczen\n");

try {

s = theServer.accept();

socketList.add(s);

DataOutputStream out = new DataOutputStream(s.getOutputStream());

DataInputStream in = new DataInputStream(s.getInputStream());

while (true) {

int n = in.read(buffor);

if (n == -1)

{

socketList.remove(s);

userList.remove(loginString);

mapa.remove(loginString);

headerOUT = "LO";

listOUT ="";

for(int i=0;i<userList.size();i++){

listOUT += (String)userList.get(i)+"#";

}

byte [] outheader = headerOUT.getBytes();

byte [] listaByte = listOUT.getBytes();

int listSize = listaByte.length;

byte [] listSizeByte = convert.int2bytearray(listSize);

byte [] outLista = new byte [2+4+listSize];

for(int i=0;i<2;i++){

outLista[i] =outheader[i];

}

for(int i=2,j=0;i<6;i++,j++){

outLista[i] =listSizeByte[j];

}

for(int i=6,j=0;i<outLista.length;i++,j++){

outLista[i] =listaByte[j];

}

for(int i=0; i < socketList.size() ;i++){

DataOutputStream out1 = new DataOutputStream(((Socket)socketList.get(i)).getOutputStream());

out1.write(outLista);

out1.flush();

}

GUI.pole.append("Zakonczono polaczenie dlawatku "+Thread.currentThread().getName()+"\n");

break;

}

outByte = new byte[n];

for(int i = 0 ;i<2;i++){

headerByte[i] = buffor[i];

}

String header = new String(headerByte);

if(header.equals("L1")){

for(int i = 2, j = 0 ;i < 6; i++ ,j++){

loginSize[j] = buffor[i];

}

int size = convert.bytearray2int(loginSize);

byte [] loginByte = new byte[size];

for(int i = 6, j = 0 ;i < 6+size; i++ ,j++){

loginByte[j] = buffor[i];

}

loginString = new String(loginByte);

int przed =mapa.size();

mapa.put(loginString,s);

int po = mapa.size();

if(przed == po){

headerOUT = "LN";

out.write(headerOUT.getBytes());

out.flush();

}else{

headerOUT = "LO";

userList.add(loginString);

listOUT = "";

for(int i=0;i<userList.size();i++){

listOUT += (String)userList.get(i)+"#";

}

byte [] outheader = headerOUT.getBytes();

byte [] listaByte = listOUT.getBytes();

int listSize = listaByte.length;

byte [] listSizeByte = convert.int2bytearray(listSize);

byte [] outLista = new byte [2+4+listSize];

for(int i=0;i<2;i++){

outLista[i] =outheader[i];

}

for(int i=2,j=0;i<6;i++,j++){

outLista[i] =listSizeByte[j];

}

for(int i=6,j=0;i<outLista.length;i++,j++){

outLista[i] =listaByte[j];

}

for(int i=0; i < socketList.size() ;i++){

DataOutputStream out1 = new DataOutputStream(((Socket)socketList.get(i)).getOutputStream());

out1.write(outLista);

out1.flush();

}

}

/*out.write(headerOUT.getBytes());

out.flush();*/

GUI.pole.append(loginString+"\n");

}

} // end while

} // end try

catch (IOException ex) {

}

} // end while

} // end run

}

SERVER GUI

-

import java.awt.event.*;

import java.io.*;

import java.net.*;

import javax.swing.*;

import java.util.*;

public class serwerGUI2 extends JFrame implements ActionListener{

JButton b1;

public JTextArea pole;

JScrollPane skrol;

//Klient_pula p;

ServerSocket theServer;

Socket s;

static int numberOfThreads = 3;

BufferedReader in;

PrintStream out,outall;

ArrayList lista;

public serwerGUI2(){

super("serwer");

this.setLayout(null);

b1 = new JButton("polocz");

b1.setSize(100,30);

b1.setLocation(10,10);

b1.addActionListener(this);

this.add(b1);

pole = new JTextArea();

skrol = new JScrollPane(pole,

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,

JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

skrol.setSize(200,200);

skrol.setLocation(150,10);

this.add(skrol);

}

public static void main(String[] args) {

serwerGUI2 frmae = new serwerGUI2();

frmae.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frmae.setSize(400,400);

frmae.setLocation(10,10);

frmae.setVisible(true);

}

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("polocz")){

try {

pole.append("Serwer zostal uruchomiony na porcie 2347 \n");

ServerSocket ss = new ServerSocket(2347);

ArrayList l = new ArrayList();

ArrayList ll = new ArrayList();

HashMap mapa = new HashMap();

//l[0] =;

for (int i = 0; i < numberOfThreads; i++) {

Serwer2 pes = new Serwer2(this,ss,l,ll,mapa);

pes.start();

//pes.w.start();

}

}

catch (IOException ex) { System.err.println(ex); }

}

}

}

-

Convert

-

import java.nio.ByteBuffer;

public class Convert {

public static byte[] int2bytearray(int i) {

byte b[] = new byte[4];

ByteBuffer buf = ByteBuffer.wrap(b);

buf.putInt(i);

return b;

}

public static int bytearray2int(byte[] b) {

ByteBuffer buf = ByteBuffer.wrap(b);

return buf.getInt();

}

}

argola at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 5

Some observations:

(a) the client ignores the result of the read: not only a possible -1 indicating that the server has closed the socket, but also the length of data read.

(b) the server never closes the socket. Both sides should close in response to a -1 result from read or an IOException or SocketException.

ejpa at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 6

> but also the length of data read.

what do mean ? check lenght of login to end char for e.g

Hader :L1

Lenght :6

Message :argol&

if betwen begin of mesage and end char & will not be 5 char close

It is ok if i close socket whene i click button or maby i should close socket in thread

argola at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 7

> in.read(buffor);

That's what I mean by ignoring the result of the read().

You can close the socket either in the thread or from another thread,

but if you do the latter and the first thread is in a blocking operation on the socket such as read(),

it will get an exception.

ejpa at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 8
whene server get -1 becouse whene i close socket in Client thread server don't get -1 but i don't have exceptionhow it should look like becouse i don't know how to solve it
argola at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 9
For the third time, because you are ignoring the result of the read() in the server. If you don't test for a condition you will never recognize it. And you should never assume that read() has filled the buffer either. This return value is there for a purpose.
ejpa at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...
# 10

i do something like that

it seems to work ok

thank you ejp for help

Client

public void actionPerformed(ActionEvent e) {

if(e.getActionCommand().equals("exit")){

petla = false;

String header = "EX";

byte [] headerByte = header.getBytes();

try {

out.write(headerByte);

out.flush();

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

*

*

*

public void run() {

while(petla){

*

*

*

}

try {

socket.close();

in.close();

out.close();

w.stop();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

argola at 2007-7-12 17:27:00 > top of Java-index,Core,Core APIs...