Hi there I am new to java and network programming... I am trying to send two UDP packets from (AssignmentChatClient) to a server (AssignmentChatServer), the server will check the first packet which contains (IP address of destination) and then forward the second packet (message) to the destination (AssignmentChatClient2). I have a problem that the destination (AssignmentChatClient2) does not receive the packet... Could you guys help me to point out where the problem is ? Thanks in advance...
Here is the code
AssignmentChatServer
import java.net.*;
import java.io.*;
public class AssignmentChatServer {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
System.out.println("Listening to socket port " + sPort);
try (DatagramSocket serverSocket = new DatagramSocket(sPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String addr = "";
String sMsg = "";
char [] tempC = null;
DatagramPacket addrPacket = null;
DatagramPacket msgPacket = null;
addrPacket = new DatagramPacket(buf, buf.length);
serverSocket.receive(addrPacket);
String address = new String(addrPacket.getData()).trim();
System.out.println(address);
tempC = address.toCharArray();
for(int i = 0; i < tempC.length; i++){
if(tempC[i] == '-'){
InetAddress sAddr = InetAddress.getByName(addr);
msgPacket = new DatagramPacket(buf2, buf2.length);
serverSocket.receive(msgPacket);
String msg = new String(msgPacket.getData());
sMsg = msg.trim();
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, cPort);
serverSocket.send(msgPacket);
System.out.println(sMsg);
addr = "";
continue;
}
addr += tempC[i];
}
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient
import java.net.*;
import java.io.*;
public class AssignmentChatClient {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf = new byte[128];
buf2 = new byte [1024];
String temp = "";
String sMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rlyPacket = null;
DatagramPacket msgPacket = null;
System.out.print("How many the number of users do you want to send to : ");
int nUsers = Integer.parseInt(input.readLine());
byte [] address = new byte [nUsers];
address = null;
System.out.print("Enter message : ");
sMsg = input.readLine();
if(sMsg == null)
return ;
for(int i = 0, j = 0; i < nUsers ; i++){
System.out.print("Please enter address " + ++j + " : ");
temp += input.readLine();
temp += "-";
}
address = temp.getBytes();
addrPacket = new DatagramPacket(address,address.length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(sMsg.getBytes(),sMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(sMsg);
// System.out.println(sAddr.toString());
rlyPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rlyPacket);
String msg = new String(rlyPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
}
}catch(IOException ex){System.out.println(ex);}
}
}
AssignmentChatClient2
import java.net.*;
import java.io.*;
public class AssignmentChatClient2 {
public static void main(String args[]) throws IOException {
int sPort = 2222, cPort = 3333;
byte[] buf = null;
byte[] buf2 = null;
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter server address : ");
String serAddress = input.readLine();
InetAddress sAddr = InetAddress.getByName(serAddress);
System.out.println("Connecting to server socket on port " + sPort);
try (DatagramSocket clientSocket = new DatagramSocket(cPort)) {
while (true) {
buf2 = new byte [1024];
String temp = "";
String replyMsg = "";
String rMsg = "";
DatagramPacket addrPacket = null;
DatagramPacket rcvPacket = null;
DatagramPacket msgPacket = null;
rcvPacket = new DatagramPacket(buf2, buf2.length);
clientSocket.receive(rcvPacket);
String msg = new String(rcvPacket.getData());
rMsg = msg.trim();
System.out.println(rMsg);
InetAddress rAddr = rcvPacket.getAddress();
temp = rAddr.toString();
System.out.print("Enter message : ");
replyMsg = input.readLine();
if(replyMsg == null)
return ;
addrPacket = new DatagramPacket(temp.getBytes(),temp.getBytes().length, sAddr, sPort);
clientSocket.send(addrPacket);
// System.out.println(temp);
msgPacket = new DatagramPacket(replyMsg.getBytes(),replyMsg.getBytes().length, sAddr, sPort);
clientSocket.send(msgPacket);
// System.out.println(replyMsg);
// System.out.println(sAddr.toString());
}
}catch(IOException ex){System.out.println(ex);}
}
}
Remember that UDP is unreliable.
You should not rely on first packet arriving before (or ever) at the recipient.
You need to provide both the final destination address and the payload in one packet.
Related
I am having trouble sending data between a UDP Server and Client, I am trying to ,send an array of strings to the client from the server. The loop that I am using will hang up and stop reading the data from the server. If i pick a small number for the loop everything is okay it works but if I try to transmit the whole string it will stop half way and the client freezes up. Here is the server it reads a file and then sends the data to the client using a loop.
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class UDPServer1
{
public static void main(String[] args) throws Exception
{
int portNumber=9999;
UDPConnection com1 = null;
InetAddress ipAddress = InetAddress.getLocalHost();
Message MS1 = new Message();
char x = 0;
int m = 12, c=0;
double q;
int percent=20;
String[] message = new String[255];
String m1;
x = (char)m;
m1 = x + ""; //turn next page character into string
double rand = Math.random();
//String ACK="";
System.out.println("Enter the percentage of packet losses will happen in the transmission: ");
//percent = MS1.getInt();
DatagramSocket ds=new DatagramSocket(portNumber);
File infile = new File("COSC635_P2_DataSent.txt");
Scanner sc = new Scanner(infile);
// we just need to use next page as delimiter
sc.useDelimiter(m1);
while(sc.hasNext() ) //get data packets
{
message[c] = sc.next()+m1;
c++;
}
System.out.println("UDP server Started ");
byte[] data = new byte[6500];
DatagramPacket receivedFrame = new DatagramPacket(data, data.length);
ds.receive(receivedFrame);
String ACK = new String(receivedFrame.getData(),0, receivedFrame.getLength());
//str = message[80];
//receiveData(ds);
//com1.setPort(receivedFrame.getPort());
portNumber = receivedFrame.getPort();
byte[] frame;
//dp1;
//System.out.println("Dp port is " + dp.getPort());
int i = 0;
while( i<=c-1) //error control goes here
{
//frame = (message[i].trim() ).getBytes();
//ipAddress = InetAddress.getLocalHost();
//DatagramPacket sendFrame= new DatagramPacket(frame, frame.length, ipAddress, receivedFrame.getPort());
sendData(ds, message[i].trim()+ACK+ " port number is " + portNumber, InetAddress.getLocalHost(), portNumber);
//ds.receive(receivedFrame);
//ACK = receiveData(ds);
//simulate lost packets
//rand = Math.random();
//q = rand*100;
//if(percent < (int)q)
//ds.send(sendFrame);
i++;
}
//frame = ("End of File").getBytes();
//ipAddress = InetAddress.getLocalHost();
//sendFrame= new DatagramPacket(frame, frame.length, ipAddress, receivedFrame.getPort());
//ds.send(sendFrame);
ds.close();
}
static String receiveData(DatagramSocket socket) throws IOException
{
byte buffer[];
buffer = new byte[6500];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 1, packet.getLength() - 1).trim();
System.out.println(received);
return received;
}
static void sendData(DatagramSocket ds, String data, InetAddress ipAddress, int portNumber) throws IOException
{
byte[] frame = null;
frame = (data.trim() ).getBytes();
DatagramPacket dp1= new DatagramPacket(frame, frame.length, ipAddress, portNumber);
//simulate lost packets
//rand = Math.random();
//q = rand*100;
//if(percent < (int)q)
ds.send(dp1);
}
}
```
Here is the code for the client.
```
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.lang.Math;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
public class UDPClient
{
public static void main(String[] args) throws Exception
{
DatagramSocket dsocket = new DatagramSocket();
String fileContent ="";
InetAddress ipAddress = InetAddress.getLocalHost();
int socketNumber=9999;
byte[] ACK = null;
FileWriter fileWriter = new FileWriter("COSC635_P2_DataRecieved.txt");
System.out.println("UDP Client Started");
String mess = "";
Message m1;
//send frames
//Frame is the string
ACK = (" ").getBytes();
DatagramPacket dp= new DatagramPacket(ACK, ACK.length, ipAddress, socketNumber);
dsocket.send(dp);
byte[] data = new byte[6500];
String str = "";
DatagramPacket dp1 = new DatagramPacket(data, data.length);
dsocket.receive(dp1);
str = new String(dp1.getData());
int i =0;
while( i<70) //error control needs to go here
{
//ds.receive(dp1);
//str = new String(dp1.getData(), 1, dp1.getLength() - 1).trim();
mess = receiveData(dsocket);
//mess = mess + " i is " + i;
System.out.println( mess.trim());
System.out.println( "inside loop");
//fileContent = fileContent + mess;
i++;
sendData(dsocket, "Packet Received " + i + " ", ipAddress, i);
}
//
//System.out.println(fileContent);
System.out.println("outside loop");
fileWriter.write(fileContent);
fileWriter.close();
dsocket.close();
System.out.println("data socket closed");
}
static String receiveData(DatagramSocket socket) throws IOException
{
byte buffer[];
buffer = new byte[6500];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
socket.receive(packet);
String received = new String(packet.getData(), 1, packet.getLength() - 1).trim();
System.out.println(received);
return received;
}
static void sendData(DatagramSocket ds, String data, InetAddress ipAddress, int portNumber) throws IOException
{
byte[] frame = null;
frame = (data.trim() ).getBytes();
DatagramPacket dp1= new DatagramPacket(frame, frame.length, ipAddress, portNumber);
ds.send(dp1);
}
}
```
I wrote a server and client for client to connect to the server and select a data from the server's directory to transfer the data with UDP protocol but the problem is, it is only working for .txt files it isn't working for .png files and also in the .txt files the output files are not the same with the original one forexample lines between words are not there and all the words printed side by side instead of line by line. How can i fix this problem ?
Server side:
import java.io.*;
import java.net.*;
public class FTPServer {
public static void main(String[] args)
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
String msg;
final int PORT = 50000;
try
{
socket = new DatagramSocket(PORT);
while(true)
{
System.out.println("\nRunning...\n");
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
int source_port=inPacket.getPort();
InetAddress source_address = inPacket.getAddress();
msg = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("CLient: " + source_address + ":" + source_port);
String dirname = "/home/erke/Desktop/data";
File f1 = new File(dirname);
File fl[] = f1.listFiles();
StringBuilder sb = new StringBuilder("\n");
int c=0;
for(int i = 0;i<fl.length;i++)
{
if(fl[i].canRead())
c++;
}
sb.append(c+ " files found.\n\n");
for(int i=0; i<fl.length;i++)
sb.append(fl[i].getName()+ " " + fl[i].length()+ " Bytes\n");
sb.append("\nEnter file name to Download: ");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
inBuf = new byte[1000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String filename = new String(inPacket.getData(), 0, inPacket.getLength());
System.out.println("Requested File: " + filename);
boolean flis = false;
int index =-1;
sb = new StringBuilder("");
for(int i=0;i<fl.length;i++)
{
if(((fl[i].getName()).toString()).equalsIgnoreCase(filename))
{
index = i;
flis = true;
}
}
if(!flis)
{
System.out.println("ERROR");
sb.append("ERROR");
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, source_address, source_port);
socket.send(outPacket);
}
else
{
try
{
//File send
File ff=new File(fl[index].getAbsolutePath());
FileReader fr = new FileReader(ff);
BufferedReader brf = new BufferedReader(fr);
String s = null;
sb=new StringBuilder();
while((s=brf.readLine())!=null)
{
sb.append(s);
}
if(brf.readLine()==null)
System.out.println("File Read Succesfull, CLosing Socket");
outBuf=new byte[100000];
outBuf = (sb.toString()).getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,source_address, source_port);
socket.send(outPacket);
} catch (Exception ioe) {
System.out.println(ioe);
}
}
}
} catch (Exception e){
System.out.println("Error\n");
}
}
}
Client side:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class FTPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket inPacket = null;
DatagramPacket outPacket = null;
byte[] inBuf, outBuf;
final int PORT = 50000;
String msg = null;
Scanner src = new Scanner(System.in);
try
{
InetAddress address = InetAddress.getByName("127.0.0.1");
socket = new DatagramSocket();
msg = "";
outBuf =msg.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length,address,PORT);
socket.send(outPacket);
inBuf = new byte[65535];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
String data = new String(inPacket.getData(), 0, inPacket.getLength());
//Print file list
System.out.println(data);
//Send file name
String filename = src.nextLine();
outBuf = filename.getBytes();
outPacket = new DatagramPacket(outBuf, 0, outBuf.length, address, PORT);
socket.send(outPacket);
//Receive file
inBuf = new byte[100000];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.receive(inPacket);
data = new String(inPacket.getData(), 0, inPacket.getLength());
if(data.endsWith("ERROR"))
{
System.out.println("File doesn't exists.\n");
socket.close();
}
else
{
try
{
BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename)));
pw.write(data);
//Force write buffer to Fİle
pw.close();
System.out.println("File Write Succesful. Closing Socket");
socket.close();
} catch (Exception ioe) {
System.out.println("File Error\n");
socket.close();
}
}
} catch (Exception e) {
System.out.println("\nNetwork Error. Try Again Later. \n");
}
}
}
In your code you are using String to store file data in both client and the server. In order to be able to transfer any file other then a text file, in your server you should have a byte[] buffer instead of String, and use it for loading file contents. You can do this by using classes with names ending with InputStream. After you do that send those bytes over a network. Same goes for the client.
InputStream and OutputStream are used to read\write bytes from files directly, while Reader and Writer classes are specifically intended to work with text files. You cannot read\write bytes with these classes, they work only with characters and strings. You will still be able to transfer text files too though since they are also just an array of bytes.
Also you should be using TCP if you want to transfer your files without losing packets, which UDP tends to do as it doesn't have mechanisms to ensure that packets are safely delivered to a destination like TCP does.
I am trying to login Ericsson MD110 alex through the c# application. The md110 returned values that asking the username for login the application, but once I pass the username and password through the following code:
public static void Main(string[] args)
{
try
{
byte[] data = new byte[1024];
string stringData;
//TcpClient tcpclnt = new TcpClient();
//Console.WriteLine("Connecting.....");
string ipaddress = "192.168.1.30";
int port=23;
IPAddress ipadd = IPAddress.Parse(ipaddress);
IPEndPoint ipend = new IPEndPoint(ipadd, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.NoDelay = false;
sock.Connect(ipend);
//recive data
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
Console.Write(stringData);
//while (true)
//{
Byte[] bBuf;
string buf;
//Application.DoEvents();
//buf = String.Format("{0}\r\n{1}\r\n", "MDUSER", "HELP");
buf = String.Format("ALREI;");
//buf = string.Format("ENTER USER NAME<.MDUSER;MDUSER;ENTER PASSWORD<.HELP;");
bBuf = Encoding.ASCII.GetBytes(buf);
sock.Send(bBuf);
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
//textBox4.AppendText(stringData + "\r\n");
string df = "";
Console.Write(stringData);
Console.ReadLine();
//}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadKey();
}
}
Further, I checked with wireshark, but md110 doesn't return any value.
only acknowledge data packet will receive.
I need some advice.
My project consists of an application using which users can send files among themselves.
Hence as a basic unit, I developed a FileServer and a FileClient Program.
This code works perfectly fine on localhost but fails on the Network (wifi).
An estimated problem is that the client socket is getting closed or isn't responding after a certain point of time while recieving. But i cant really figure out what the problem is or how to approach the problem.
The error appears is a SocketException: Software caused connection abort. Socket write error.
FileServer CODE:
import java.net.*;
import java.io.*;
public class FileServerPC {
static String remoteIPaddress = "192.168.43.95";
static String filename;
String path;
static File selectedfile = null;
static ServerSocket servsock = null;
static Socket sock = null;
static FileInputStream fis;
static BufferedInputStream bis;
static DatagramSocket theSocket = null;
static DatagramPacket theOutput;
static OutputStream os;
byte[] mybytearray;
static double nosofpackets;
static int packetsize = 1024;
public FileServerPC() {
try {
servsock = new ServerSocket(1500);
theSocket = new DatagramSocket(9999);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
FileServerPC fs = new FileServerPC();
selectedfile = new File("C:\\flower.jpg");
filename = selectedfile.getName();
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Waiting...");
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
fis = new FileInputStream(selectedfile);
System.out.println((int) selectedfile.length());
long length = selectedfile.length();
System.out.println("LENGTH: " + length);
nosofpackets = Math
.ceil(((int) selectedfile.length()) / packetsize);
// progressBar.setValue(50);
bis = new BufferedInputStream(fis);
String message = length + "`~`" + filename;
byte[] data = message.getBytes();
theOutput = new DatagramPacket(data, data.length,
InetAddress.getByName(remoteIPaddress),8888);
theSocket.send(theOutput);
byte[] newbytearray = new byte[packetsize];
int dur = (int) (selectedfile.length());
int dur1 = dur / 100;
int counter = 0;
System.out.println("duration: " + dur + "nosofpackets: "
+ nosofpackets + "dur1: " + dur1);
int val = 0;
for (int i = 0; i <= nosofpackets ; i++) {
os = sock.getOutputStream();
bis.read(newbytearray, 0, newbytearray.length);
os.write(newbytearray, 0, newbytearray.length);
counter = counter + newbytearray.length;
val = counter / dur1;
System.out.println(val);
os.flush();
}
System.out.println(val);
os.flush();
os.close();
sock.close();
theSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
}
FileClient CODE:
import java.net.*;
import java.io.*;
public class FileClientPC
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
String remoteip="192.168.43.237";
Socket sock = new Socket(remoteip, 1500);
System.out.println("Connecting...");
InputStream is = sock.getInputStream();
DatagramSocket ds = new DatagramSocket(8888);
byte[] buffer = new byte[65507];
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
try {
ds.receive(dp);
} catch (IOException e) {
System.err.println("chat error2 " + e);
}
String s = new String(dp.getData(), 0, dp.getLength());
String temp[]=s.split("`~`");
String size = temp[0];
String name = temp[1];
System.out.println(size +" "+ name);
long sizeint = Integer.parseInt(size);
System.out.println("Filename: " + name);
FileOutputStream fos = new FileOutputStream("D:\\"+name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int packetsize = 1024;
double nosofpackets = Math.ceil(sizeint / packetsize);
System.out.println("No of packets: "+Double.toString(nosofpackets));
byte newbytearray[];
for (int i = 0; i <= nosofpackets; i++) {
is = sock.getInputStream();
newbytearray = new byte[packetsize];
int bytesRead = is.read(newbytearray, 0, newbytearray.length);
System.out.println("Packet:" + (i + 1));
bos.write(newbytearray, 0, newbytearray.length);
}
long end = System.currentTimeMillis();
bos.close();
sock.close();
ds.close();
}
}
You need to specify which interface you want to listen to. The default is the local interface. (probably OS dependent). The API for ServerSocket explains how this works (the constructor and bind() functions for instance).
I'm trying to transfer an ArrayList from a client to a server using the UDP protocol.
The transfer starts at the "max" if statement.
Same in the server side
This is the client:
public class UdpClient {
protected DatagramPacket sendPacket;
protected DatagramPacket receivePacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpClient upd = new UdpClient();
ArrayList<Integer> arr = new ArrayList<Integer>();
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
ByteArrayOutputStream bStream = new ByteArrayOutputStream();
ObjectOutput oo = new ObjectOutputStream(bStream);
ByteArrayInputStream baos;
ObjectInputStream oos;
System.out
.println("Commands: Time, Date, Weather, Sum-number, Max-number, Exit");
while (true) {
String fromUsr = inFromUser.readLine();
if (fromUsr.equals("bye")) {
break;
} else if (fromUsr.equals("weather")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
System.out
.println("Please select a ctiy: Lund, Malmo, Stockholm");
String weather = inFromUser.readLine();
sendData = weather.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
} else if (fromUsr.equals("max")) {
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
String max = inFromUser.readLine().trim();
upd.nums(max, arr);
oo.writeObject(arr);
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
upd.sendPacket(buf, clientSocket);
System.out.println(arr);
} else {
// send data that of the user
sendData = fromUsr.getBytes();
upd.sendPacket(sendData, clientSocket);
upd.receivePacket(clientSocket, receiveData);
}
String fromServer = new String(upd.getData());
System.out.println("Message from server:\n" + fromServer);
}
}
private void sendPacket(byte[] sendData, DatagramSocket clientSocket)
throws IOException {
InetAddress IPAddress = InetAddress.getByName("ericman-PC");
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress,
9876);
clientSocket.send(sendPacket);
}
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
byte[] rData = new byte[1024];
receiveData = rData;
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
This is the Server
public class UdpServer {
protected DatagramPacket receivePacket;
protected DatagramPacket sendPacket;
public static void main(String args[]) throws IOException,
ClassNotFoundException {
UdpServer upd = new UdpServer();
DatagramSocket serverSocket = new DatagramSocket(9876);
DateFormat currentDate = new SimpleDateFormat("yyyy/MM/dd");
DateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
ByteArrayInputStream baos;
ObjectInputStream oos;
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true) {
System.out.println("****************************************"
+ "\nServer is connected");
upd.receivePacket(serverSocket, receiveData);
String str = new String(upd.getData()).trim();
System.out.println("Message received is:" + " " + str);
if (str.equals("time")) {
str = currentTime.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("date")) {
str = currentDate.format(date);
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("weather")) {
upd.receivePacket(serverSocket, receiveData);
str = upd.weather(str = new String(upd.getData()).trim());
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
} else if (str.equals("max")) {
byte[] buf = new byte[1024];
System.out.println("waitng for object to come");
upd.receivePacket(serverSocket, buf);
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
Object o = oos.readObject();
System.out.println(o);
} else {
str = "Unknown command, please try again..";
sendData = str.getBytes();
upd.sendPacket(serverSocket, sendData);
}
}
}
This is the error i get in the Server side
Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at UdpServer.main(UdpServer.java:54)
Line 54 that the error indicates is this line on the server
baos = new ByteArrayInputStream(buf);
oos = new ObjectInputStream(baos);
If you could help me out of why this error is happening? thanx!
Your code creates alot of arrays it immediately discards. I would use a debugger to step through the code so you understand what it is doing.
private void receivePacket(DatagramSocket serverSocket, byte[] receiveData)
throws IOException {
// create a new array
byte[] rData = new byte[1024];
// throw away the orignal array so the new array will be update.
receiveData = rData;
// copy into the new array, not the old one.
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
}
In this case, the original receiveData will not me modified so it will contain lots of 0 bytes.
byte[] buf = new byte[bStream.toByteArray().length];
buf = bStream.toByteArray();
This creates three arrays when all you need is one. The first array bStream.toByteArray() is created just so you can determine what length it would be. You create a second array which is the same length but empty and put it in buf Finally you discard the second array and replace it with a copy of the first array.