I have a client and server, I can send data to the server but I need help on how I can use the data received from the client to draw a graph using Plot2DPanel/JMathPlot. a simple code on how I can assign data received from the client to Plot2DPanel. I have the code below, which receives data from the client but I don't how can I use this on Plot2DPanel.
while(true){
System.out.println("Waiting for the incoming mesages" +portNumber+ "....");
receiveSocket.receive(receivedPacket);
IAddress address = receivedPacket.getAddress();
int clientPort = receivedPacket.getPort();
String message = new String(receivedPacket.getData());
message = message.trim();
System.out.println("The message {+mesage+}.\n\t\t The message is received from host: " +IAddress+ "on port" + portNumber);
byte[] sendData = new byte[256];
String sendBackMessage = "Thank you, message was received";
sendData = sendBackMessage.getBytes();
receivedPacket = new DatagramPacket(sendData, sendData.length, IAddress, clientPort);
receiveSocket.send(receivedPacket);
Related
my programm is establishing a connection via multicastsocket between server and client. I want to send some informations to the client and then receive an answer from the client and print it out.
This works, but it always printing out the String infromation. Like it is still saved in the DatagramPacket and fill the String received with data from String information. So when i run the programm its always printing out "Server: received Message: Welcome to the Event Server"
System.out.println("Server is running...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info_socket = new MulticastSocket(3456);
info_socket.joinGroup(infoChannel);
String information = "Welcome to the Event Server ";
byte [] buffer = information.getBytes();
DatagramPacket info_packet = new DatagramPacket(buffer, buffer.length, infoChannel, 3456);
info_socket.send(info_packet);
System.out.println("Message send");
while(true) {
info_packet.setData(new byte[256]);
info_socket.receive(info_packet);
String received = new String(info_packet.getData(), info_packet.getOffset(), info_packet.getLength());
info_packet.setLength(info_packet.getLength());
System.out.println("Server: received Message: " + received);
}
CLient :
System.out.println("Client is waiting for Connection to Server...");
InetAddress infoChannel = InetAddress.getByName("225.5.6.6");
MulticastSocket info = new MulticastSocket(3456);
info.joinGroup(infoChannel);
byte[] buffer = new byte[350];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
info.receive(packet);
String recString = new String(buffer);
String[] lines = recString.split("#");
Arrays.stream(lines).forEach(System.out::println);
System.out.println("Enter message to send: ");
String answer = readIn.nextLine();
packet = new DatagramPacket(answer.getBytes(), answer.length(), infoChannel, 3456);
info.send(packet);
System.out.println("client: Inormation sended to Server");
info.close();
Thanks in advance!
i tried to somehow clear the buffer and then store the received message in the String received
I am trying to create a a client and server chat program using UDP. I have followed a tutorial making a similar program using TCP and tried to then translate my knowledge over to make one in similar fashion using UDP.
I have completed a client and server side with both showing no errors and will run, but once running neither will message the other or receive messages... can someone help me see what i'm doing wrong?
Server side for sending messages:
try{
//creates the packet to be sent
byte[] buf = new byte[256];
String msgout = serverText.getText().trim();
buf = msgout.getBytes();
//uses the socet.receive method to get the packet to retrieve information to send
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
//uses packet information to create and send packet
DatagramPacket packetSend = new DatagramPacket(buf, buf.length, address, port);
ss.send(packetSend);
//Displays the message in the chat area and clears the text area
serverArea.setText(serverArea.getText().trim()+"\n Server: "+msgout);
serverText.setText("");
}catch (Exception e){
}
and then the main for setting the socket and receiving/printing:
String msgin = "";
try{
ss = new DatagramSocket(1420); // Sets socket at 1420
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
ss.receive(packet); //Receives the packet from the socket
//Converts the byte array into a string
String clientMsg = new String(packet.getData(), 0, packet.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
serverArea.setText(serverArea.getText().trim()+"\n Client: "+msgin); //displays client message
}
}catch(Exception e){
}
Here is the client side code, ill combine its send and receive areas into one block:
try{
//Creates the message out using the known socket that the Server creates and the known local address
String msgout = clientText.getText().trim();
sendBuf = msgout.getBytes();
InetAddress address = InetAddress.getLocalHost();
DatagramPacket sp = new DatagramPacket(sendBuf, sendBuf.length, address, 1420);
s.send(sp);
//Displays the text and clears the text field
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgout);
clientText.setText("");
}catch (Exception e){
}
String msgin = "";
try{
//Creates a socket
DatagramSocket s = new DatagramSocket();
//Receives the message from the server
byte[] buf = new byte[256];
DatagramPacket rp = new DatagramPacket(buf, buf.length);
s.receive(rp);
//Converts byte array to message
String clientMsg = new String(rp.getData(), 0, rp.getLength());
while(!msgin.equals("exit")){
//Displays the message
msgin = clientMsg;
clientchat.setText(clientchat.getText().trim()+"\n Server: "+msgin); //displays client message
}
}catch (Exception e){
}
Any help and tips will be greatly appreciated!
If nothing is happening, and you are unable to send/receive messages, it is likely that there are exceptions that are being generated.
However, since you have a try-catch block that catches all exceptions, and then simply does nothing, you will have no idea what exceptions are thrown, if any are thrown at all.
Rather than simply ignoring exceptions, you should at least be printing their cause.
In your catch statements, add the following and you will be able to more easily debug.
e.printStackTrace();
In my Android App I'm using DatagramSockets to send messages to a server like this:
InetAddress address = InetAddress.getByName(host);
byte[] byteMessage = (" " + message + "\r\n##!!##").getBytes();
DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length, address, port);
DatagramSocket socket = new DatagramSocket();
try
{
socket.send(packet);
}
finally
{
socket.close();
}
But only every N-1th packet is sent.
Meaning if I send 1 packet, nothing is sent. If I send the second, the first one gets send. If I send the third, the second gets send etc etc.
EDIT:
So after the first comments I a) got rid of the useless throw-statement b) tried not closing the socket after sending. It doesn't help.
So as an example for clarification: The following code works perfectly and I receive the package server-side. But it's obviously not a pretty solution...
InetAddress address = InetAddress.getByName(host);
byte[] byteMessage = (" " + message + "\r\n##!!##").getBytes();
DatagramPacket packet = new DatagramPacket(byteMessage, byteMessage.length, address, port);
DatagramSocket socket = new DatagramSocket();
try
{
socket.send(packet);
String emptyMessage = " ";
socket.send(new DatagramPacket(emptyMessage.getBytes(), emptyMessage.getBytes().length, address, port));
}
finally
{
socket.close();
}
I'm just sending a second "empty" message afterwards. I first tried sending an empty byte array, but that does not work.
How can broadcast a message from single server to multiple clients and listen for a reply from one of the clients.
I used Multicast Programming to broadcast the message to the clients. And If i send the message from one of my clients back to the server either through TCP or UDP, I am getting a "java.net.ConnectException: Connection refused: connect" exception.
Please help me out.
Thanks in Advance.
Sender Code :
// Broadcasting the message
msg = "This is multicast! " + counter;
counter++;
outBuf = msg.getBytes();
// Send to multicast IP address and port
InetAddress address = InetAddress.getByName("224.2.2.3");
outPacket = new DatagramPacket(outBuf, outBuf.length, address,
PORT);
socket.send(outPacket);
System.out.println("Server sends : " + msg);
socket.close();
// Receiving TCP
apSock = new Socket("131.151.88.165", 6161);
apBuffReader = new BufferedReader(new InputStreamReader(
apSock.getInputStream()));
while ((ap2Toap1 = apBuffReader.readLine()) != null) {
System.out.println(ap2Toap1);
}
Receiver Code :
count++;
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String msg = new String(inBuf, 0, inPacket.getLength());
System.out.println("From " + inPacket.getAddress() + " Msg : "
+ msg);
socket.close();
// Sending TCP
apSock = new Socket("131.151.88.165", 6161);
System.out.println("Hello2");
respWriter = new PrintWriter(apSock.getOutputStream());
System.out.println("Writing back to the server");
respWriter.println(outBuf);
if (respWriter != null)
respWriter.close();
There is no listening in your code. TCP listening in Java is accomplished via a ServerSocket. You aren't using one. Instead you're using Sockets at both ends. So what you have is two clients and no server. No communication is possible between two TCP clients.
I'm devolping an SMS application that uses UDP protocol . My application need to do the following , client send to another client a message doesn't exceed 160 and he/she know the other client IP address . It will send through a server which will save it in case client is offline .
I started working on it but then I stopped ! I was having problem with these things .
How can multiple clients sends to server ? I searched about and I read about something called mutithreading , can anyone explain or give me example for it ?
also , I couldn't imagin the process of taking messages from clients and then saving it . I mean how the server know which message belong to which client ?
this is the code which I'm working on it
server :
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String senderSentence = "From "+IPAddress+" Msg "+sentence;
sendData = senderSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
} } }
client :
import java.io.*;
import java.net.*;
public class Client {
public static void main(String args[]) throws Exception
{
String sentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
do {
System.out.println("Enter a msg , NOTE: don't exceed 160 charcter");
sentence = inFromUser.readLine();
}
while(sentence.length() >= 160);
System.out.println("Enter the adress of the other user");
String ip=inFromUser.readLine();
InetAddress IPAddress = InetAddress.getByName(ip);
sendData = sentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
} }
Thank you ~
I'm not sure why you need to use UDP - but if this isn't some special requirement you might want to look at using a web server.
I quite like the Play Framework for Java, which is going to handle the threading for you. Every time you send a message to the server it is just like sending a request for a web page, so you can reply with JSON or XML or whatever you think is best.
This is going to be a lot easier than handling all the socket communication yourself - but as I say, maybe you have a special requirement.
Hope this helps!