Was writing a server for my X O game. The basic idea was that I have one computer run as a server wit ha static ip and others could connect to it.
It needs to be able to send the state of the game to all the connected clients, but I ran into a blocking problem.
If you take a look at the client side
Scanner input = new Scanner();
int test = input.nextInt();
is blocking the code.
The server is able to send the message to all the clients but it is being prevented by the nextInt() as it waits for the Int to be passed in order to echo the state of the game(jsut a set of ints, coordinates).
Could anyone help me out here, I am really stuck, have been reading up on blocking problems, on the net and here on the forums I found that some people were saying that I have to check the inputStream on the client side whether it contains something or not but I could not implement it.
Any idea, suggestions are welcomed.
Thank you all for your time.
-------SERVER-----------
import java.net.*;
import java.io.*;
public class Server extends SerResponse {
public static void main(String[] args) {
int port = 1234;
int cliNum = 1;
try {
ServerSocket sock = new ServerSocket(port);
System.out.println("SERVER WORKING......");
int index0 = 0;
while (true) {
SerResponse ser = new SerResponse();
Socket connection = sock.accept();
soc[index0] = connection;
index0++;
if (connection != null) {
System.out.println("Client " + cliNum + " connected " + connection);
cliNum++;
}
Runnable runnable = new Server(connection, ++ser.count);
Thread t = new Thread(runnable);
t.start();
}
} catch (Exception e) {
System.out.println("SERVER FAIL " + e);
}
}
public Server(Socket s, int count) {
this.connection = s;
this.ID = count;
}
}
------SERVER RESPONSE--------------
import java.io.*;
import java.net.Socket;
public class SerResponse implements Runnable {
public static Socket connection;
public int ID;
public final static int size = 10;
public static Socket[] soc = new Socket[size];
public int count = 0;
public int test;
public void run() {
try {
while (true) {
DataInputStream in = new DataInputStream(connection.getInputStream());
test = in.readInt();
System.out.println("Recieved from " + connection + " " + test + "\n");
for (int index0 = 0; index0 < size; index0++) {
if (soc[index0] != null) {
DataOutputStream out = new DataOutputStream(soc[index0].getOutputStream());
out.writeInt(test);
System.out.println("Sent to client " + soc[index0] + " " + test);
}
}
}
} catch (Exception e) {
System.out.println("Runnable FAIL " + e);
}
}
}
-----CLIENT--------
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class client {
public static void main(String[] args) {
int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
int[][] arr1 = new int[3][2];
int port = 1234;
int test;
int test1;
try {
System.out.println("Starting client");
Socket sock = new Socket("localhost", port);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
DataInputStream in = new DataInputStream(sock.getInputStream());
Scanner input = new Scanner(System.in);
int turn = 0;
while (true) {
test = input.nextInt();
out.writeInt(test);
System.out.println(test);
test1 = in.readInt();
System.out.println(test1);
turn++;
}
} catch (Exception e) {
System.out.println("CLIENT FAIL " + e);
}
}
}
Here's a rework of your client class that should give the asynchronous behaviour that you're looking for.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client extends Thread {
private final Socket sock;
private boolean shutdown = false;
public Client(Socket sock) {
this.sock = sock;
}
public void shutdown() {
shutdown = true;
}
public void writeDataToServer(int test) {
try {
synchronized(Client.class) {
//don't allow reading and writing at the same time.
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeInt(test);
sock.getOutputStream().flush();
}
}catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
BufferedInputStream bis = new BufferedInputStream(sock.getInputStream());
while(!shutdown) {
if(bis.available() > 0) {
synchronized(Client.class) {
DataInputStream in = new DataInputStream(bis);
int test = in.readInt();
//you can do something with test hereafter.... but since the example just had it printing out
System.out.println(test);
}
} else {
Thread.sleep(500); //sleep for 500ms before polling again.
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
sock.close();
} catch(Exception ignored){}
}
}
public static void main(String[] args) {
int[][] arr = {{3, 4}, {6, 2}, {9, 2}};
int[][] arr1 = new int[3][2];
int port = 1234;
int test;
try {
System.out.println("Starting client");
Client client = new Client(new Socket("localhost", port));
client.start();
Scanner input = new Scanner(System.in);
int turn = 0;
while(turn < 10) {
test = input.nextInt();
client.writeDataToServer(test);
System.out.println(test);
turn++;
}
client.shutdown();
} catch(Exception e) {
System.out.println("CLIENT FAIL " + e);
}
}
}
Related
I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.
I'm trying to make a simple program with a server and client, passing text strings back and forth. I'm having trouble making the connection. I have a test printing line right below the socket accept line and it never prints, so I assume the problem is there, but I'm not sure how to do a more thorough check.
I have written this program in Eclipse if that makes a difference.
This is the server:
import java.io.*;
import java.net.*;
public class HW2Q1S {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
//data xfer
BufferedReader sIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter sOut = new PrintWriter(skt.getOutputStream(), true);
//string receiving
int count = 1;
String msg = "";
while((msg = sIn.readLine()) != null) {
while(count < 11) {
msg = sIn.readLine();
System.out.println("Received: "+ msg);
String returnMsg = msg.toUpperCase();
System.out.println("Capped: "+ returnMsg);
sOut.write(returnMsg);
count++;
}
} //end of read from client in while loop
if (count == 10) {
System.out.println("Max reached.");
}
srvr.close();
return;
}
catch(Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
And this is the client:
import java.util.Random;
import java.io.*;
import java.net.*;
public class HW2Q1C {
public static void main(String[] args) throws IOException {
String capped = "";
String temp = "";
try {
//make the connection
Socket skt = new Socket("localhost", 7654);
BufferedReader cIn = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintWriter cOut = new PrintWriter(skt.getOutputStream(), true);
//send 11 strings
for (int i = 0; i < 11; i++) {
temp = Stringer();
cOut.write(temp);
System.out.println("Sending: " + temp);
}
//receive server strings
while(cIn.readLine() != null) {
capped = cIn.readLine();
System.out.println("From server: "+ capped);
}
skt.close();
} // end of connection try block
catch(Exception e) {
System.out.print("Whoops! It didn't work!\n");
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
Thanks!
I think I found your problem.
You should use println instead of write. I am quite sure the problem is that write does not send an actual line string + \n and therefore the server cannot read a line.
I modified your example a little bit to make it easier to test and understand, but this works for me:
Server:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
try {
//connection
ServerSocket srvr = new ServerSocket(7654);
Socket skt = srvr.accept();
System.out.println(skt.getPort());
BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream()));
String msg = "";
while ((msg = in.readLine()) != null) {
System.out.println("Received: " + msg);
} //end of read from client in while loop
srvr.close();
} catch (Exception e) {
System.out.println("Error caught: " + e);
}
} // end of main
} // end of class
Client:
import java.util.Random;
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
try {
Socket socket = new Socket("localhost", 7654);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
for (int i = 0; i < 11; i++) {
out.println(Stringer()); //<-- println instead of write
}
socket.close();
} // end of connection try block
catch(Exception e) {
System.out.print(e.toString());
}
} //end of main
static String Stringer() {
String msg, alpha;
msg = "";
alpha = "abcdefghijklmnopqrstuvwxyz";
Random rnd = new Random();
for (int i = 0; i < 10; i++) {
msg += alpha.charAt(rnd.nextInt(25));
}
return msg;
}
} //end of class
ServerOutput:
Received: scnhnmaiqh
Received: tuussdmqqr
Received: kuofypeefy
Received: vghsinefdi
Received: ysomirnfit
Received: lbhqjfbdio
Received: qhcguladyg
Received: wihrogklfi
Received: tipikgfvsx
Received: fmpdcbtxqb
Received: yujtuefqft
I've got a working simple client-server app. The problem is it works fine just with one started client, but not with two or more. It establish connection, but when you try to enter text in first or second, the server breakes. I think that problem may be at the function broadcast() in Server.java.
Server.java
public class Server {
final int PORT = 5000;
private ArrayList<NewClient> al = new ArrayList<NewClient>();
private Scanner in;
private PrintWriter out;
private SimpleDateFormat sdf;
private int uniqueID = 0;
private void go(){
try{
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
while(true) {
Socket s = serverSocket.accept();
NewClient chat = new NewClient(s);
System.out.println("Client number " + chat.getId() + " connected from: " + s.getLocalAddress().getHostName());
al.add(chat);
Thread t = new Thread(chat);
t.start();
}
}catch (Exception e) {
System.out.println("Problem with establishing network connection: ");
e.printStackTrace();
}
}
public static void main(String[] args) {
Server server = new Server();
server.go();
}
class NewClient implements Runnable{
private Socket socket;
private int id;
public NewClient(Socket s) {
this.socket = s;
this.id = ++uniqueID;
}
public int getId() {
return this.id;
}
#Override
public void run() {
try{
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
sdf = new SimpleDateFormat("HH:mm:ss");
while(true) {
String input = in.nextLine();
System.out.println("Client said: " + input);
broadcast(input);
}
}catch (Exception e) {
e.printStackTrace();
}
}
private void writeMsg(String input) {
String msg = input + " on " + sdf.format(new Date());
out.println("You said: " + msg);
out.flush();
}
private void broadcast(String input) {
for (int i = 0; i < al.size(); i++) {
NewClient t = al.get(i);
t.writeMsg(input);
}
}
}
}
Client.java:
public class Client {
final int PORT = 5000;
final String HOST = "127.0.0.1";
private Scanner stdIn;
private Scanner in;
private PrintWriter out;
private void go() {
setUpNetwork();
}
private void setUpNetwork(){
try{
Socket s = new Socket(HOST, PORT);
System.out.println("You are connected to " + HOST);
NewClient client = new NewClient(s);
Thread t = new Thread(client);
t.start();
} catch (Exception e) {
System.out.println("Problem with connection to server: " + e);
}
}
public static void main(String[] args) {
Client client = new Client();
client.go();
}
class NewClient implements Runnable {
private Socket socket;
public NewClient(Socket s) {
this.socket = s;
}
#Override
public void run() {
try {
stdIn = new Scanner(System.in);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
while(true) {
System.out.print("> ");
String input = stdIn.nextLine();
out.println(input);
out.flush();
if(in.hasNext()) {
System.out.println(in.nextLine());
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
When opens two Client.java and connect it to the server.java everything is ok. But when i try to send some message from this two opened clients server returns these errors:
java.lang.IndexOutOfBoundsException: end
at java.util.regex.Matcher.region(Matcher.java:1038)
at java.util.Scanner.findPatternInBuffer(Scanner.java:1010)
Client said: sds
at java.util.Scanner.findWithinHorizon(Scanner.java:1679)
at java.util.Scanner.nextLine(Scanner.java:1538)
at Server$NewClient.run(Server.java:66)
at java.lang.Thread.run(Thread.java:745)
What's happening is that your code scans the first line from the client ("sds", which is printed to stdout), and then it loops back and immediately tries to scan the next line from the client. Since the client hasn't sent anything more yet, the input stream scanner throws an exception.
The NewClient class is an inner class. All instances of this class are created with the same instance of the outer class. Changing the code will sove the problem:
public NewClient(Socket s) {
this.socket = s;
this.id = ++uniqueID;
try{
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream());
sdf = new SimpleDateFormat("HH:mm:ss");
}catch(Exception e) {
System.out.println("Exception while creating input/output streams: " + e);
}
}
I developed a simple, multi-threaded proxy server. Note that this program is a proxy for one specific server. Here is my code :
public class Proxy {
int remotePort;
InetAddress remoteHost;
public Proxy(InetAddress remoteHost, int remotePort) {
this.remotePort = remotePort;
this.remoteHost = remoteHost;
}
public void go() {
ExecutorService pool = Executors.newCachedThreadPool();
try (ServerSocket server = new ServerSocket(2015);) {
System.out.println("Proxy is running....!");
while (true) {
Socket socketClient = server.accept();
System.out.println("client connected...!");
Socket socketServer = new Socket(remoteHost, remotePort);
System.out.println("connection established with the server...!");
Worker p1 = new Worker(socketClient, socketServer);
Worker p2 = new Worker(socketServer, socketClient);
pool.execute(p1);
pool.execute(p2);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
class Worker implements Runnable {
Socket from, to;
public Worker(Socket from, Socket to) {
this.from = from;
this.to = to;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName());
try (BufferedInputStream bis = new BufferedInputStream(from.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(to.getOutputStream());) {
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
from.close();
to.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
public static void main(String[] args) {
InetAddress adr = null;
try {
adr = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
}
new Proxy(adr, 2020).go();
}
}
I would like to test this proxy server with a client and a server. the client sends an array of integers to find the maximum. the server of his turn, returns the maximum of a received array.
the problem is the following: the proxy server is not playing its role. the array is not sent to the server and the client not received the maximum value of its array.
The code of my Server is as follow:
public class ServerTCPMax {
static void display(int[] tab) {
for (int u : tab) {
System.out.print(u + " ");
}
System.out.println();
}
static int searchMax(int[] t) {
int max = t[0];
for (int i = 1; i < t.length; i++) {
if (t[i] > max) {
max = t[i];
}
}
return max;
}
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(2020);
System.out.println("server is running .......! ");
while (true) {
try (Socket sclient = server.accept()) {
System.out.println("Proxy connected...!");
ObjectInputStream ois = new ObjectInputStream(sclient.getInputStream());
int[] tab = (int[]) ois.readObject();
display(tab);
int max = searchMax(tab);
try (DataOutputStream dos = new DataOutputStream(sclient.getOutputStream())) {
dos.writeInt(max);
dos.flush();
}
}
}
} catch (IOException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
}
The following code represents my client:
public class ClientTCPMax {
public static void main(String[] args) {
int[] A = {3, -7, 9, 22, 0, 7, 11, 2};
try {
try (Socket socket = new Socket("127.0.0.1", 2015)) {
System.out.println("connection established with the Proxy ...!");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(A);
oos.flush();
DataInputStream dis = new DataInputStream(socket.getInputStream());
int max = dis.readInt();
System.out.println(" the max is : " + max);
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Ok so I have constructed a working example of a client and server which can accept multiple client connections. My problem is is that I cannot connect a client which is not running the same internet connection as the one the server is being hosted on. Is this possible using server sockets?
Here is the code for my server:
import java.io.IOException;
import java.net.*;
public class MultipleSocketServer {
public static Socket connection;
public static String name = "Tyler's Server";
public static int limit = 2;
public static Thread[] clients = new Thread[limit];
public static int current = 0;
public static int port = 25565;
public static String[] connected = new String[limit];
public static ServerSocket socket;
public static void main(String[] args) {
System.out.println("Server starting...");
for(int i = 0; i < limit; i++) {
connected[i] = "";
}
try {
ServerSocket socket = new ServerSocket(port);
while(true) {
Socket connection = socket.accept();
String ip = connection.getRemoteSocketAddress().toString().substring(1, 13);
loop:
for(int i = 0; i < connected.length; i++) {
if(connected[0].equals(ip) || connected[1].equals(ip)) {
break loop;
}else if(!connected[i].equals(ip)) {
connected[i] = ip;
MultiServer_Client client = new MultiServer_Client(connection, i);
Thread run = new Thread(client);
run.start();
break loop;
}
}
}
} catch (IOException e1) {
System.out.println("Could not bind server on: " + port);
System.exit(-1);
}
}
}
And here is the rest:
import java.io.*;
import java.net.Socket;
public class MultiServer_Client implements Runnable {
public String time;
public Socket client;
public StringBuffer process = new StringBuffer();
public BufferedInputStream inputStream;
public InputStreamReader reader;
public BufferedOutputStream outputStream;
public OutputStreamWriter writer;
public StringVis check = new StringVis("");
public StringChangeListener checkListener = new StringChangeListener() {
public void textChanged(StringChangeEvent e) {
System.out.println("Changed");
write("Server recieved message...");
}
};
public boolean connected = true;
public int ID;
public MultiServer_Client(Socket connection, int i) {
client = connection;
ID = i;
try {
//declare text input/output
inputStream = new BufferedInputStream(client.getInputStream());
reader = new InputStreamReader(inputStream);
outputStream = new BufferedOutputStream(client.getOutputStream());
writer = new OutputStreamWriter(outputStream, "US-ASCII");
} catch (IOException e) {
System.out.println("IOException: " + e);
}
System.out.println(MultipleSocketServer.connected[ID] + " connected...");
write("Connected to " + MultipleSocketServer.name);
}
public void run() {
while(connected) {
read();
}
System.out.println("Disconnecting client...");
}
public void write(String authen) {
try {
time = new java.util.Date().toString();
String message = time + ": " + authen + (char) 13;
writer.write(message);
writer.flush();
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
public void read() {
//read from client
int character;
process = new StringBuffer();
try {
while ((character = reader.read()) != 13) {
process.append((char) character);
}
check.setText(process.toString());
process.delete(0, process.length());
} catch (IOException e) {
connected = false;
MultipleSocketServer.connected[ID] = "";
}
}
}
Here's the client code:
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class SocketClient {
public static String host = "69.182.134.79";
public static int port = 25565;
public static void main(String [] args) {
StringBuffer imports = new StringBuffer();
String time;
System.out.println("Client starting...");
try {
//establish client
InetAddress address = InetAddress.getByName(host);
Socket connection = new Socket(address, port);
BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
while(true) {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
//write to server
time = new java.util.Date().toString();
String process = host + ":" + port + " sent data at " + time + ": " + message + (char) 13;
osw.write(process);
osw.flush();
//read from server
int c;
while ((c = isr.read()) != 13) {
imports.append((char) c);
}
System.out.println(imports);
imports.replace(0, imports.length(), "");
if(message.equals("--EXIT")) {
connection.close();
}
}
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: " + e);
} catch (IOException e) {
System.out.println("IOExcepion: " + e);
}
}
}
Change
MultiServer_Client client = new MultiServer_Client(connection, i);
to
MultiServer_Client client = new MultiServer_Client(new Socket([Server IP], port), i);
This should work.