I write chat on sockets. The application consists of two parts, a client and an echo server. The Message object is sent.
There is a problem: the encoding is spoiled after the text is transmitted over the socket, that is, you cannot write in Russian letters. I tried a lot of ways except the standard system.out.print (). Nothing helped.
Here is a serializable object.
public class Message implements Serializable{ private String text; public Message(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
Echo server:
class Server { ServerSocket serverSocket; private ObjectInputStream ois ; private ObjectOutputStream oos ; Message message; public void start() throws IOException, ClassNotFoundException { this.serverSocket = new ServerSocket(2345); Socket socket = serverSocket.accept(); ois = new ObjectInputStream(socket.getInputStream()); oos = new ObjectOutputStream(socket.getOutputStream()); while(true) { message = (Message) ois.readObject(); System.out.println( message.getText()); oos.writeObject(message); } } }
Customer:
class Client extends Thread{ Scanner scanner = new Scanner(System.in); Socket socket; private ObjectInputStream ois = null; private ObjectOutputStream oos = null; public void startClient() throws IOException { this.socket = new Socket("localhost" , 2345); oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); this.start(); String string = ""; while ( !string.equals("exit") ) { string = scanner.nextLine(); oos.writeObject(new Message(string)); } } @Override public void run() { Message message; try { while (true) { message = (Message) ois.readObject(); System.out.println(message.getText()); } } catch(Exception e) {} } }
Help solve the problem with the encoding.