I’m working on an online game. For communication between clients and the server, I’m using TCP. Now, when clients send their usernames to the server, the server should message them back ‘1’, but the client receives ‘�� 1’.
This is the server:
package org.example;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
public class TCPServer {
static ServerSocket serverSocket;
public static void main(String[] args) {
System.out.println("server is running....");
//
// Start the server
// try {
// server.start();
// System.out.println("WebSocket server started. Press any key to stop...");
// System.in.read(); // Keep the server running
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// server.stop();
// }
//
int port=1234;
try{
serverSocket=new ServerSocket(port);
while (true){
Socket clientSocket=serverSocket.accept();
System.out.println("a client connected");
new ClientHandler(clientSocket).start();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
static class ClientHandler extends Thread{
private final Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
public void run() {
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(),"UTF-8"), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(clientSocket.getOutputStream())) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("received " + inputLine);
Client client=new Client(inputLine,clientSocket);
Squad squad=new Squad(client);
Client test1=new Client("test1",clientSocket);
Squad stest1=new Squad(test1);
Client test2=new Client("test2",clientSocket);
Squad stest2=new Squad(test2);
stest1.clients.add(client);
stest1.clients.add(test2);
//
squad.clients.add(test1);
squad.clients.add(test2);
String connected="1";
out.println(connected);
System.out.println("connected: "+connected);
// objectOutputStream.writeObject("connected to server");
send_list_of_squads(objectOutputStream);
String request=receive_message(clientSocket);
String[] array=request.split("/");
if(array[0].equalsIgnoreCase("11" )){
if ( !client.isInSquad()){
String Owner=array[1];
for(int i=0;i<Squad.Squads.size();i++){
if(Squad.Squads.get(i).getOwner().getUserName().equalsIgnoreCase(Owner)){
Client owner=Squad.Squads.get(i).getOwner();
send_message(owner.getSocket(),"11/"+client.getUserName());
String message=receive_message(owner.getSocket());
if(message=="0"){
owner.getSquad().clients.add(client);
send_message(client.getSocket(),"Accepted in the squad");
} else if (message=="1") {
send_message(client.getSocket(),"Your request denied");
}
}
}
}
} else if (array[0].equalsIgnoreCase("22")) {
new Squad(client);
System.out.println("a new squad created for "+client.getUserName());
send_message(client.getSocket(),"a new squad created for "+client.getUserName());
}
// send_list_of_clients_in_squad(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void send_list_of_squads(ObjectOutputStream oos) throws IOException {
System.out.println("list of squads sent");
// ObjectOutputStream outputStream=new ObjectOutputStream(socket.getOutputStream());
ArrayList<HashMap<String,Integer>> sendingList= new ArrayList<>();
System.out.println("squads size in server: "+Squad.Squads.size());
for(int i=0;i<Squad.Squads.size();i++){
HashMap<String,Integer> map=new HashMap<>();
map.put(Squad.Squads.get(i).getOwner().getUserName(),Squad.Squads.get(i).clients.size());
sendingList.add(map);
}
System.out.println("size of sending map in server: "+sendingList.size());
oos.writeObject(sendingList);
oos.flush();
}
public static String receive_message(Socket socket) throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(socket.getInputStream()));
return bf.readLine();
}
public static void send_message(Socket socket,String message) throws IOException {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(message);
}
}
This is the client:
package org.example;
import javax.swing.*;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class TCP {
static Socket socket;
private String uername="";
public String getUername() {
return uername;
}
public void setUername(String uername) {
this.uername = uername;
}
public static void main(String[] args) throws IOException {
}
public TCP() throws IOException {
socket=new Socket("localhost",1234);
this.setUername(JOptionPane.showInputDialog(null,"USERNAME: "));
System.out.println("after getting username");
TCP.sendMessage(getUername());
System.out.println("after sending username");
// PrintWriter printWriter=new PrintWriter(socket.getOutputStream(),true);
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
// if(getUername()!=null) {
Client.setClient(new Client(getUername()));
new Thread(() -> {
try {
String response;
Scanner scanner=new Scanner(socket.getInputStream());
while ((response =reader.readLine()) != null) {
System.out.println( response);
System.out.println("result: "+response.equalsIgnoreCase("1"));
String[] array = response.split("/");
// if (!response.isEmpty()) {
if (response.equalsIgnoreCase("1")) {
ArrayList<HashMap<String, Integer>> receiving = TCP.get_list_of_squads(socket);
System.out.println("this is size of list of owners: " + receiving.size());
String[] squads = new String[receiving.size()];
for (int i = 0; i < receiving.size(); i++) {
HashMap<String, Integer> map = receiving.get(i);
for (String key : map.keySet()) {
squads[i] = key + ": " + map.get(key);
}
}
System.out.println("size of squads list item: " + squads.length);
JList<String> itemList = new JList<>(squads);
itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
itemList.setBounds(0, 30, 300, 500);
SquadFrame.getSquadFrame().add(itemList);
itemList.addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
//
String chosen_squad = itemList.getSelectedValue();
try {
TCP.sendMessage("11/" + getUername() + "/" + chosen_squad);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
JOptionPane.showMessageDialog(null, "request sent to " + chosen_squad);
}
});
}
//
else if (array[0] == "11") {
JOptionPane.showMessageDialog(SquadFrame.getSquadFrame(), "Received from server: " + response);
int response_of_request = JOptionPane.showConfirmDialog(null, "wants to join to your squad. Would you accept?", "acception", JOptionPane.YES_NO_OPTION);
if (response_of_request == JOptionPane.YES_OPTION) {
TCP.sendMessage("0");
} else if (response_of_request == JOptionPane.NO_OPTION) {
TCP.sendMessage("1");
} else {
System.out.println("client closed the dialog");
}
}
// else{
// JOptionPane.showMessageDialog(null,response);
// }
// }
System.out.println("Received from server: " + response);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}).start();
// }
}
public static void sendMessage(String message) throws IOException {
System.out.println("sending message is: "+message);
PrintWriter printWriter=new PrintWriter(socket.getOutputStream());
printWriter.println(message);
printWriter.flush();
}
public static String getMessage(){
String str="";
InputStreamReader in= null;
try {
in = new InputStreamReader(socket.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
BufferedReader bf=new BufferedReader(in);
try {
str=bf.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
public static ArrayList<HashMap<String,Integer>> get_list_of_squads(Socket socket) throws IOException, ClassNotFoundException {
System.out.println("getting list of squads");
ArrayList<HashMap<String,Integer>> receiving=new ArrayList<>();
System.out.println("before inputsreaem" );
ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
System.out.println("afetr inputsreaem" );
System.out.println("instance : " + (in.readObject() instanceof ArrayList<?>));
if(in.readObject() instanceof ArrayList<?>){
System.out.println("in is array List");
receiving=(ArrayList<HashMap<String, Integer>>) in.readObject();
}
// String[] squads=(String[]) in.readObject();
System.out.println("size of receiving in tcp: "+receiving.size());
return receiving;
}
public static String[] get_list_of_clients() throws IOException, ClassNotFoundException {
ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
String[] clients=(String[]) in.readObject();
return clients;
}
public static void send_requist_for_squad(){
}
}
I checked the encoding and set it to ‘UTF-8’ for both the server and client, but I still have a problem.