Я таки разобрался в чём причина была. Соединение терялось так как была ошибка записывания/считывания потока BufferedReader/PrintWriter, из-за этого сокет на стороне клиента разрывал соединение (скорее всего ошибка была связана с освобождением ресурсов потоков или как-то так (если например записать/считать потоки а потом применить метод сокета close(), то всё норм, следовательно в close() правильно обращается с потоками в отличие от меня)).Вот рабочий вариант, если кому интересно. Сервер
Код |
public class Server { public static void main(String[] args) { // TODO Auto-generated method stub try{ int i=0; ServerSocket s=new ServerSocket(8189); System.out.println("Server is started"); while(true) { User u=new User(i,s.accept()); u.start(); i++; System.out.println(i); } } catch(IOException e) { System.out.println("init error: "+e); }
} }
|
Код | public class User extends Thread{ Socket s; int num; InputStream is; OutputStream os; BufferedReader br; PrintWriter out; int count=0; public User(int i,Socket s) { num=i; this.s=s; } public void run() { try { BufferedReader in = new BufferedReader( new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true);
out.println("Hello, you are client #" + num + "."); out.println("Enter a line with only a period to quit\n"); while (true) { String input = in.readLine(); Server.history=Server.history+"\n"+input; if (input == null || input.equals(".")) { break; } out.println(input.toUpperCase()); } } catch (IOException e) { log("Error handling client# " + num + ": " + e); } finally { try { s.close(); } catch (IOException e) { log("Couldn't close a socket, what's going on?"); } log("Connection with client# " + num + " closed"); } }
private void log(String message) { System.out.println(message); } }
|
Клиент (написанный с использованием Swing и SWT(SWT для Eclipse(нужно подключить библиотеку org.eclipse.swt))
Код | public class Klient { public static void main(String[] args) { new SwingView(); //new SWTView(); } }
|
Код | public class SwingView { JButton send; JButton connect; JTextArea server; JTextField message; JFrame frame; JTextArea history; private BufferedReader in; private PrintWriter out; public SwingView() { frame=new JFrame("клиент"); send=new JButton("отправить"); connect=new JButton("соединение"); server=new JTextArea("127.0.0.1/8189"); message=new JTextField("сообщение"); history=new JTextArea(); frame.setSize(400,400); JPanel panel=new JPanel(); panel.setLayout(new GridLayout(2, 2)); panel.add(server); panel.add(connect); panel.add(message); panel.add(send); Box box=new Box(BoxLayout.Y_AXIS); box.add(panel); box.add(history); frame.add(box,BorderLayout.NORTH); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); connect.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); start(); } }); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { send(); } }); } public void start() { try { Socket s = new Socket(getHost(), getPort()); in = new BufferedReader( new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); for (int i = 0; i < 3; i++) { System.out.println(in.readLine() + "\n"); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void send() { out.println(message.getText()); String response; try { response = in.readLine(); if (response == null || response.equals("")) { System.exit(0); } } catch (IOException ex) { response = "Error: " + ex; } history.setText(response); message.selectAll(); } public int getPort() { String p=server.getText(); int port=Integer.parseInt(p.substring(p.indexOf("/")+1, p.length())); return port; } public String getHost() { String p=server.getText(); return p.substring(0,p.indexOf("/")); }
}
|
Код | public class SWTView { private BufferedReader in; private PrintWriter out; Button send; Button connect; Text serverName; Text message; Text history; Thread t; boolean flag=false; public SWTView() { Display display = new Display(); Shell shell = new Shell(display); shell.setText("SWT Hello"); shell.setSize(400, 400); Group border = new Group(shell, SWT.SHADOW_OUT); FillLayout fillLayout=new FillLayout(SWT.VERTICAL); shell.setLayout(fillLayout); GridLayout gridLayout = new GridLayout(2, true); border.setLayout(gridLayout); serverName = new Text(border, SWT.LEFT); connect = new Button(border, SWT.RIGHT); connect.setText("Подключиться"); message = new Text(border, SWT.LEFT); send = new Button(border, SWT.RIGHT); send.setText("Отправить"); history = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL); message.setLayoutData(new GridData(SWT.FILL, 60, true, true)); serverName.setLayoutData(new GridData(SWT.FILL, 60, true, true)); connect.setLayoutData(new GridData(SWT.FILL, 60, true, true)); send.setLayoutData(new GridData(SWT.FILL, 60, true, true)); serverName.setText("127.0.0.1/8189"); message.setText("ksfksdhfgkdfgdfljk"); send.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { send(); } }); connect.addMouseListener(new MouseAdapter() { @Override public void mouseUp(MouseEvent e) { start(); } }); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } public void start() { try { Socket s = new Socket(getHost(), getPort()); in = new BufferedReader( new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); for (int i = 0; i < 3; i++) { System.out.println(in.readLine() + "\n"); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void send() { out.println(message.getText()); String response; try { response = in.readLine(); if (response == null || response.equals("")) { System.exit(0); } } catch (IOException ex) { response = "Error: " + ex; } history.setText(response); message.selectAll(); } public int getPort() { String p=serverName.getText(); int port=Integer.parseInt(p.substring(p.indexOf("/")+1, p.length())); return port; } public String getHost() { String p=serverName.getText(); return p.substring(0,p.indexOf("/")); }
}
|
Осталось добавить историю сообщений. Спасибо всем, кто пытался помочь. |