The sequence numbers aren't working as the int value seems to reset to 0 - or setting it again in the second method returns an error.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1651)
at Client3.sendThenReceive(Client3.java:106)
at Client3.stopAndWait(Client3.java:69)
at Client3.main(Client3.java:41)
This is the client:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.nio.*;
public class Client3 {
private DatagramSocket datagramSocket;
private InetAddress inetAddress;
private byte [] buffer;
private int initialSequenceNumber = 100;
private int sequenceNumber;
private int testSN;
private static final int port = 1234;
private static final int BUFFER_SIZE = 1024;
private static final String HOSTNAME = "localhost";
private static String message;
public Client3(DatagramSocket datagramSocket, InetAddress inetAddress) {
this.datagramSocket = datagramSocket;
this.inetAddress = inetAddress;
}
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress inetAddress = InetAddress.getByName(HOSTNAME);
Client3 client = new Client3(datagramSocket, inetAddress);
System.out.println("Send datagram packets to a server");
Scanner scanner = new Scanner(System.in);
message = (scanner.nextLine() + " Umbrella");
scanner.close();
client.stopAndWait();
}
public void stopAndWait() throws IOException {
Client3 client = new Client3(datagramSocket, inetAddress);
sequenceNumber = initialSequenceNumber;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
toSend.writeInt(sequenceNumber);
buffer = test.toByteArray();
DatagramPacket testConnection = new DatagramPacket(buffer, buffer.length, inetAddress, port);
System.out.println("testConnection sent, waiting for confirmation.");
datagramSocket.send(testConnection);
datagramSocket.receive(testConnection);
ByteArrayInputStream confirmConnection = new ByteArrayInputStream(testConnection.getData());
DataInputStream dis = new DataInputStream(confirmConnection);
int SN = dis.readInt();
//test code to show the received data to the console
//System.out.println(SN);
if (SN == sequenceNumber) {
System.out.println("Confirmation received. Proceeding to Message delivery.");
//testSN = sequenceNumber;
//System.out.println("test: " + testSN + " SN: " + sequenceNumber);
client.sendThenReceive();
}
else {
System.out.println("error - incorrect sequence number.");
}
}
public void sendThenReceive() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
// Changing the variable here results in error and termination
//Is it because it is in the method?
//int newNumber = 101;
//testSN = 101;
//sequenceNumber = 101;
ByteArrayOutputStream test = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(test);
System.out.println("test: " + testSN + " SN: " + sequenceNumber);
toSend.writeInt(sequenceNumber);
toSend.writeUTF(message);
buffer = test.toByteArray();
System.out.println(message + " " + sequenceNumber);
DatagramPacket sentMessage = new DatagramPacket(buffer, buffer.length, inetAddress, port);
datagramSocket.send(sentMessage);
datagramSocket.receive(sentMessage);
ByteArrayInputStream test2 = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test2);
int SN = dis.readInt();
String messageFromServer = dis.readUTF();
if (SN == 101) {
System.out.println("The server says you said: " + messageFromServer);
sequenceNumber++;
Scanner newScanner = new Scanner(System.in);
message = (newScanner.nextLine() + " Umbrella");
newScanner.close();
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
} scanner.close();
}
}
And this is the server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.io.*;
import java.net.*;
import java.nio.*;
public class Server3 {
private DatagramSocket datagramSocket;
private byte[] dataForSend = new byte[256];
byte[] receiveData = new byte[ dataForSend_SIZE ];
//byte[] dataForSend = new byte[ dataForSend_SIZE ];
private int initialSequenceNumber = 100;
private int sequenceNumber;
private static final int port = 1234;
private static final int dataForSend_SIZE = 1024;
public static void main(String[] args) throws IOException {
DatagramSocket datagramSocket = new DatagramSocket(port);
Server3 server = new Server3(datagramSocket);
System.out.println("Server Operational");
server.testConnection();
}
public Server3(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
public void testConnection() throws IOException {
while (true) {
try {
sequenceNumber = initialSequenceNumber;
DatagramPacket receivedMessage = new DatagramPacket (receiveData, receiveData.length);
datagramSocket.receive(receivedMessage);
InetAddress inetAddress = receivedMessage.getAddress();
int port = receivedMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(receivedMessage.getData());
DataInputStream dis = new DataInputStream(test);
int a10 = dis.readInt();
System.out.println("SN read from Datagram: " + a10);
if ( a10 == sequenceNumber) {
System.out.println("Connection Test Successfully Received.");
ByteArrayOutputStream confirmConnection = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(confirmConnection);
toSend.writeInt(sequenceNumber);
dataForSend = confirmConnection.toByteArray();
DatagramPacket testConnection = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(testConnection);
System.out.println("'confirmConnection' has been sent.");
sequenceNumber++;
receiveThenSend();
}
else {
System.out.println("error - incorrect sequence number."); }
}
finally {
}
}
}
public void receiveThenSend() throws IOException {
while (true) {
try {
sequenceNumber = 101;
DatagramPacket sentMessage = new DatagramPacket(receiveData, receiveData.length);
datagramSocket.receive(sentMessage);
InetAddress inetAddress = sentMessage.getAddress();
int port = sentMessage.getPort();
ByteArrayInputStream test = new ByteArrayInputStream(sentMessage.getData());
DataInputStream dis = new DataInputStream(test);
int SN = dis.readInt();
System.out.println("SN received: " + SN);
System.out.println("SN on File: " + sequenceNumber);
String messageFromClient = dis.readUTF();
if (SN == sequenceNumber) {
//String messageFromClient = new String(sentMessage.getData(), 0, sentMessage.getLength());
System.out.println("SN: Match.");
System.out.println("Message from Client: " + messageFromClient);
System.out.println("Response sent.");
ByteArrayOutputStream serverResponse = new ByteArrayOutputStream();
DataOutputStream toSend = new DataOutputStream(serverResponse);
toSend.writeInt(101);
toSend.writeUTF(messageFromClient);
dataForSend = serverResponse.toByteArray();
sentMessage = new DatagramPacket(dataForSend, dataForSend.length, inetAddress, port);
datagramSocket.send(sentMessage);
}
else {
System.out.println("Error - incorrect sequence number.");
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
}
Can anyone see why these would be resetting, please?
The Exception you're getting is caused by closing the Scanner. When a Scanner instance is closed, it closes the underlying stream which is System.in in your case.
So next time when you create the Scanner, it's created over a closed stream and .nextLine() throws the exception you're seeing.
Here's a snippet that reproduces the issue:
Scanner s1 = new Scanner(System.in);
s1.close();
Scanner s2 = new Scanner(System.in);
s2.nextLine(); //Exception in thread "main" java.util.NoSuchElementException: No line found
Related
I am learning Java networking and am trying to implement a simple UDP server-client program which exchanges messages between server and client. The program is working, but when I print the buffer, a lot of newlines get printed. What am I doing wrong? Here is my code for the server:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.net.SocketException;
class Q1Server {
private DatagramSocket ds;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
private InetAddress clientIP;
private int clientPort;
public Q1Server() throws SocketException{
ds = new DatagramSocket(1234);
buff1 = new byte[10000];
buff2 = null;
while(true) {
try {
dp1 = new DatagramPacket(buff1, buff1.length);
System.out.println("Waiting for connection...");
ds.receive(dp1);
System.out.print(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
clientIP = dp1.getAddress();
clientPort = dp1.getPort();
System.out.println("Connected to IP: " + clientIP + " Port: " + clientPort);
buff2 = ("Thanks for connecting to the server!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
String cl = "";
while (!cl.equals("close")) {
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println("here");
cl = new String(buff1, "UTF-8");
buff1 = new byte[10000];
System.out.println("Client: " + cl);
}
buff2 = ("Closing...\nGoodbye!!!").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, clientIP, clientPort);
ds.send(dp2);
} catch(IOException i) {
i.printStackTrace();
}
}
}
public static void main(String[] args) throws SocketException {
Q1Server server = new Q1Server();
}
}
And here is the code for client:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
class Q1Client {
private DatagramSocket ds;
private Scanner scanner;
private InetAddress ip;
private byte[] buff1, buff2;
private DatagramPacket dp1 = null, dp2 = null;
public Q1Client() throws SocketException, UnknownHostException {
ds = new DatagramSocket();
ip = InetAddress.getLocalHost();
buff1 = new byte[10000];
buff2 = null;
scanner = new Scanner(System.in);
try {
buff2 = ("Start").getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
buff1 = new byte[10000];
String msg = "";
while(!msg.equals("close")) {
System.out.println("here");
msg = scanner.nextLine();
System.out.println("Typed: " + msg);
buff2 = msg.getBytes(StandardCharsets.UTF_8);
dp2 = new DatagramPacket(buff2, buff2.length, ip, 1234);
ds.send(dp2);
}
dp1 = new DatagramPacket(buff1, buff1.length);
ds.receive(dp1);
System.out.println(new String(buff1, "UTF-8"));
} catch(IOException i) {
i.printStackTrace();
}
}
public static void main(String[] args) throws SocketException, UnknownHostException{
Q1Client client = new Q1Client();
}
}
I think the problem may be due to the size of the buffer. The byte buffer array is pre-initialized with the size that large than the actual text being sent. But what is the other way to do it? How do I know the size of the buffer dynamically?
I was trying a simple problem of sending some random numbers from server to client by UDP Broadcasting. As far as I know, if I broadcast to a specific ip address and port number, all the users who are connected to that channel will be able to listen. I have looked for sample codes in the internet and developed my code based on that. But whenever I try to run the codes, my server closes the socket before client can get anything.
The server code is:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.SecureRandom;
public class Server {
public static void main(String[] args) throws IOException {
DatagramPacket packet;
InetAddress address;
DatagramSocket socket;
System.out.println("Sending Numbers!");
socket = new DatagramSocket();
try {
int n = 10;
SecureRandom rand = new SecureRandom();
address = InetAddress.getByName("233.0.0.1");
for(int i = 0; i < n; i++)
{
int num = rand.nextInt(100);
byte[] tmp = Integer.toString(num).getBytes();
packet = new DatagramPacket (tmp, 0, address, 1502);
socket.send(packet);
System.out.println("Number has been sent!");
}
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
try {
socket.close();
} catch (Exception e) {
System.out.println("Error2: " + e);
}
}
}
}
The client code is:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
public class Client {
public static void main(String[] args) throws IOException {
// Initialization
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
DatagramPacket packet = null;
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
byte[] numb = packet.getData();
int num = ByteBuffer.wrap(numb).getInt();
System.out.println(Integer.toString(num));
}
}
}
Then, I tried to compile each code using javac and java.
javac Server.java
java package_name.Server
I am running the Server first using the above method, then Client. I get NullPointerException for client. It would be really helpful if I understand what am I doing wrong here.
I am running them in command window. For server, I get this
Server
And for Client: Client
Edit: I was able to communicate between Server and Client. However, I just keep getting the first number only. Moreover, if I initialize Datagram for size >2, I get NumberFormatException. This is the improved code.
Server Code:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.security.SecureRandom;
public class Server {
public static void main(String[] args) throws IOException {
DatagramPacket packet;
InetAddress address;
DatagramSocket socket;
System.out.println("Sending Numbers!");
socket = new DatagramSocket();
try {
int n = 10;
SecureRandom rand = new SecureRandom();
address = InetAddress.getByName("127.0.0.1");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream pout = new PrintStream( bout );
for(int i = 0; i < n; i++)
{
int num = rand.nextInt(100);
pout.print(num);
byte[] barray = bout.toByteArray();
packet = new DatagramPacket (barray, barray.length, address, 1502);
socket.send(packet);
System.out.println("Number has been sent!");
System.out.println(num);
}
} catch (Exception e) {
System.out.println("Error: " + e);
} finally {
try {
socket.close();
} catch (Exception e) {
System.out.println("Error2: " + e);
}
}
}
}
Client Code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class Client {
public static void main(String[] args) throws IOException {
// Initialization
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
byte[] buf = new byte[2];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
int num = Integer.parseInt(new String(packet.getData()));
System.out.println(num);
}
}
}
What can be the issue now?
Edit 2: Finally, I have made it work. Just put bout and pout inside the for loop and it should work!
you need to initialize your DatagramPacket in your client - it can not be null
int n = 10;
// Create the socket
int port = 1502;
DatagramSocket socket;
byte[] buf = new byte[1000];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket = new DatagramSocket(port);
for (int i = 0; i < n; i++)
{
socket.receive (packet);
byte[] numb = packet.getData();
int num = ByteBuffer.wrap(numb).getInt();
System.out.println(Integer.toString(num));
}
Also this code needs to be running before your Server
Here are my 2 different programs that connect to each other:
SERVER
package authenticateddns;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class Server {
public static final int PORT = 4444;
int clientNumber;
static String[][] url = new String[8][2];
public static void main(String args[]) throws IOException {
url[0][0] = "www.google.com";
url[0][1] = "172.217.11.174";
url[1][0] = "www.facebook.com";
url[1][1] = "31.13.77.36";
url[2][0] = "www.youtube.com";
url[2][1] = "74.125.65.91";
url[3][0] = "www.wikipedia.org";
url[3][1] = "91.198.174.192";
url[4][0] = "www.twitter.com";
url[4][1] = "199.59.149.230";
url[5][0] = "www.amazon.com";
url[5][1] = "72.21.211.176";
url[6][0] = "www.yahoo.com";
url[6][1] = "98.137.149.56";
url[7][0] = "www.abc.com";
url[7][1] = "199.181.132.250";
new Server().runServer();
}
public void runServer() throws IOException {
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("Server up and ready for connection...");
while (true) {
ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
Socket socket = serverSocket.accept();
pool.submit(() -> new ServerThread(socket, clientNumber, url).start());
System.out.println("New client has joined");
clientNumber++;
}
}
}
SERVERTHREAD
package authenticateddns;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerThread extends Thread {
Socket socket;
String clientName;
int clientN;
String url[][];
byte[] message = new byte[4];
ServerThread(Socket socket, int clientNumber, String[][] url)
{
this.socket = socket;
clientN = clientNumber;
this.url=url;
message[0]=1;
message[1]=2;
message[2]=3;
message[3]=4;
}
public void run()
{
try
{
String userURL;
String ip = "";
clientName = "Client" + clientN;
//this is from the server
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//this is from the client
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
//dout.writeInt(message.length);
//dout.write(message);
//this reads in from client
while(true)
{
if((userURL = bufferedReader.readLine()) != null)
{
userURL = userURL.replace("\n", "").replace("\r", "");
for(int i = 0; i < 8; i++)
{
if(url[i][0].equals(userURL))
{
ip = url[i][1];
break;
}
if(!url[i][0].equals(userURL)&&i==7)
{
ip = "IP Address not found";
}
}
//System.out.println(clientName);
System.out.println(" " + clientName + ": Desired URL: " + userURL);
System.out.println(" " + clientName + ": Sending IP: " + ip);
System.out.println("");
//send this to client
printWriter.println("Server Recieved Message");
printWriter.println(ip);
dout.write(message);
System.out.println("worked");
}
//socket.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
AND THEN YOU HAVE THE CLIENT PROGRAM
package client;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.InetAddress;
public class Client {
public static void main(String[] args) throws IOException
{
//InetAddress localIP;
//localIP = InetAddress.getLocalHost();
//Socket socket = new Socket("10.0.36.89", 4444);
Socket socket = new Socket("10.1.43.10", 4444);
String ip;
String confirm;
int length;
// from client
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
BufferedReader buffedReader = new java.io.BufferedReader(new InputStreamReader(System.in));
//from server
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataInputStream din = new DataInputStream(socket.getInputStream());
while(true)
{
//this sends input
System.out.print("Enter Destired URL: ");
String readerInput = buffedReader.readLine();
readerInput = readerInput.replace("Enter Destired URL: ", "");
printWriter.println(readerInput);
if((confirm = bufferedReader.readLine()) != null)
{
System.out.println(confirm);
}
//this reads in from server
if((ip = bufferedReader.readLine()) != null)
{
System.out.println("Server returns IP Address: " + ip);
System.out.println("");
}
int j = 4;
byte[] message = new byte[4];
if(j>0)
{
din.readFully(message, 0, 4); // read the message
j=j-1;
}
for(int i = 0; i < 4; i++)
{
System.out.print(message[i]);
}
}
}
}
The issue is that the client is not receiving the byte array. It only works if you run the Server program in debugger and put a breakpoint on where it writes to Client.
Does anyone have any ideas?
I send information to the server, the server hangs for all eternity, any guidance is much appreciated. I think the problem is with one of the conidtional statements or the dataoutputstream but idk.
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public Client(Socket newSocket, int ID) {
// Set properties
id = ID;
socket = newSocket;
connected = true;
// Get input
inport = new Inport();
inport.start();
}
public static int conversion(int serverValue) {
if (serverValue >= 10) {
return 10;
} else
return serverValue;
}
/**
* Handles all incoming data from this user.
*/
private class Inport extends Thread {
private ObjectInputStream in;
//private DataInputStream in;
public void run() {
// Open the InputStream
try {
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
System.out.println("Could not get input stream from " + toString());
return;
}
// Announce
System.out.println(socket + " has connected input.");
// Enter process loop
while (true) {
// Sleep
try {
} catch (Exception e) {
System.out.println(toString() + " has input interrupted.");
}
}
}
}
static String standOrHit = "";
private Socket socket;
private boolean connected;
private Inport inport;
static int serverValue;
static String serverName = "127.0.0.1"; //Our Server Name
static String selection = "";
static int port = 9999; //Our Server
static Scanner keyboard = new Scanner(System.in);
static boolean isTurn = true;
static boolean isGameOver = false;
static int score = 0;
static String sh = "It's your turn. Enter 'H' for Hit or 'S' for stand) \n Score:" + score;
static int id = 500;
public static void main(String[] args) throws IOException {
System.out.println("Fetching server connection...");
Socket client = new Socket(serverName, port); //Create a Client Socket and attempt to connect to the server # port
System.out.println("Connection Established.");
System.out.println("Fetching Player ID...");
System.out.println("Game Found you're Player " + 3 + ".");
System.out.println("Waiting for server...");
OutputStream outputStream = client.getOutputStream(); //Create a stream for sending data
DataOutputStream out = new DataOutputStream(outputStream); //Wrap that stream around a DataOutputStream
//InputStream is used for reading
InputStream inputStream = client.getInputStream(); //Read the incoming stream as bytes
DataInputStream dataInputStream = new DataInputStream(inputStream); //Read the inputStream and convert to primative times
// while (isGameOver == false) {
//Ask the User if what they want to do
System.out.println(sh);
selection = keyboard.nextLine();
//If they choose H
//if (selection.equals("H")) {
//Send the H to the Server(Works)
out.writeUTF(selection);
out.flush();
//Add server score to our score
// System.out.println(dataInputStream.readUTF());
while (dataInputStream.available() > 0) {
serverValue = dataInputStream.readInt();
}
score += conversion(serverValue);
System.out.println("Drew a " + serverValue + ".");
System.out.println("Waiting for player " + id);
//Loop back until
// }
//If they choose to stand just send S
if (selection.equals("S"))
{
//Send the H to the Server(Works)
out.writeUTF(selection);
out.flush();
}
// }
}
}
Server
import java.net.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
/**
*
*/
public class Server extends Thread implements Runnable{
private ServerSocket serverSocket;
private Socket socket;
private ArrayList<Client> clients = new ArrayList<Client>();
private boolean isGameOver = false;
private Random rand;
private int scoreToAdd;
public Server(int port) throws IOException
{
serverSocket = new ServerSocket(port,2);
rand = new Random();
}
//Thread to execute once t.Start is called
public void run()
{
//Just as we are awaiting,print to the user.
System.out.println("Server started. Finding Clients...");
//System.out.println("Waiting for client on port : " + serverSocket.getLocalPort() + " ... ");
Socket server = null;
DataOutputStream dataOutputStream ;
//InputStream is used for reading
InputStream inputStream; //Read the incoming stream as bytes
DataInputStream dataInputStream; //Read the inputStream and convert to primative times
try {
//If the server is accepted, connect the user
//System.out.println("Connection Established.");
// Get a client trying to connect
server = serverSocket.accept();
//dataOutputStream = new DataOutputStream(server.getOutputStream());
//inputStream = server.getInputStream();
//dataInputStream = new DataInputStream(inputStream);
// Client has connected
System.out.println("Found Client "+ (clients.size()+1));
// Add user to list
clients.add(new Client(server,1));
}
catch (IOException e)
{
e.printStackTrace();
}
while (true)
{
try {
socket = serverSocket.accept();
dataOutputStream = new DataOutputStream(server.getOutputStream());
inputStream = server.getInputStream();
dataInputStream = new DataInputStream(inputStream);
// Client has connected
System.out.println("Found Client "+ (clients.size()+1));
System.out.println("Initiating Game...");
// Add user to list
clients.add(new Client(socket,1));
clients.get(0).isTurn = true;
while(isGameOver == false || ((clients.get(0).standOrHit.equals("S") && clients.get(1).standOrHit.equals("S")) == false))
{
if(clients.get(0).isTurn) {
System.out.println("Player 1's Turn");
if (dataInputStream.readUTF().equals("H")) {
//Generate a random number (Works)
System.out.println("Got H from Client");
//Send the random number in a outputbuffer (Works)
dataOutputStream.write(rand.nextInt(13) + 1);
dataOutputStream.flush();
clients.get(0).isTurn = false;
clients.get(1).isTurn = true;
}
}
else if (clients.get(1).isTurn)
{
System.out.println("Player 2's Turn");
if(dataInputStream.readUTF().equals("H"))
{
//Generate a random number (Works)
//System.out.println(rand.nextInt(13)+1);
//Send the random number in a outputbuffer (Works)
dataOutputStream.write(rand.nextInt(13)+1);
dataOutputStream.flush();
clients.get(1).isTurn = false;
clients.get(0).isTurn = true;
}
}
}
//Read input from the client
//DataInputStream dataInputStream = new DataInputStream(server.getInputStream());
//If we decide to hit
//if(dataInputStream.readUTF().equals("1"))
//{
//We want to send a random score 1-14
//rand = new Random();
// temp = rand.nextInt(14);
//}
//DataOutputStream dataOutputStream = new DataOutputStream(server.getOutputStream());
//dataOutputStream.writeUTF(Integer.toString(temp));
//dataOutputStream.flush();
// server.close();
}
catch (IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = 9999;
try
{
Thread t = new Server(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
i have 2 class
first class
import java.io.IOException;
import java.net.*;
public class Udp {
DatagramSocket socket = null;
DatagramPacket inPacket = null; // recieving packet
DatagramPacket outPacket = null; // sending packet
byte[] inBuf, outBuf;
InetAddress source_address = null;
public String Hasil = null;
String msg;
final int PORT = 8888;
public void received() {
try {
socket = new DatagramSocket(PORT);
while (true) {
System.out.println("Waiting for client...");
// Receiving datagram from client
inBuf = new byte[256];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
// Extract data, ip and port
int source_port = inPacket.getPort();
source_address = inPacket.getAddress();
msg = new String(inPacket.getData(), 0, inPacket.getLength());
// System.out.println("Client " + source_address + ":" + msg);
Hasil = msg;
// Send back to client as an echo
msg = reverseString(msg.trim());
outBuf = msg.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,
source_address, source_port);
socket.send(outPacket);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Client " + source_address + ":" + msg);
}
private static String reverseString(String input) {
StringBuilder buf = new StringBuilder(input);
return buf.reverse().toString();
}}
and second class
public class main {
public static void main(String[] args) {
Udp u = new Udp();
u.received();
System.out.println(u.Hasil + " " + u.source_address);
}
}
why when i run this porgram, udp is start , but String Hasil not comming,
how i can get String Hasil in statement While (true) ?
your string may null try this structure:
while(true){
while(hasil==null){
}
}
You need seperate threads:
public class Udp implements Runnable {
boolean running = false;
...
while(running) { // <-- this was your while (true) {
...
#Override
public void run {
running = true
received();
}
public void stop() {
running = false;
}
}
and in your main
...
new Thread(u).start();
while(u.Hasil != null){
try{
Thread.currentThread().sleep(1);//sleep for 1 ms
}
catch(ItrerruptedException ie){
//ignore
}
}
yeah i know the style is ugly ;)