Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem in using the Socket I/O function

Status
Not open for further replies.

wayne2004

Programmer
Apr 17, 2003
6
HK
Hi, I am new to JAVA and this time I am going to develop an application that employ the java stream socket, My problem is that I can successfully create a server socket, create a socket and connect to them together. but for the inputstream and outputstream, I don't know if it has problem with my coding or otherwise, I cannot read and write the data to the stream . As I try to do so, the
java.io.nullpointerException appear and the program cease
I attached the source code for reference:

===========================================================
/*
* ThreadSend.java
*
* Created on April 2, 2003, 3:48 PM
*/

import java.util.*;
import java.net.*;
import java.lang.*;
import java.io.*;
/**
*
* @author
*/
public class ThreadSend extends Thread {
//private int MAX_PACKETSIZE = 1024;

private int packetsize; // in byte
private long rate; // rate of send being called.
private int packets; //number of packets to be sent
private int packetSent; //number of packets being sent
private int port;
private boolean bSend;
private DatagramPacket UDPpacket;
private DatagramSocket UDPsocket;
private InetAddress addr;
private Socket TCPclient;
private OutputStream Out ;


private int seq;
private byte mBuffer[];
private byte tempBuffer[];
private boolean bAlways;
private int protocol;


/** Creates a new instance of ThreadSend */
public ThreadSend(long rate, int packetsize, int packets, int port, String peer_addr, int protocol) {
this.rate = rate;
this.packetsize = packetsize;
this.packets = packets;
this.port = port;
this.protocol = protocol;
seq = 0;

mBuffer = new byte[packetsize];
//mBuffer = new byte[MAX_PACKETSIZE];

bSend = true;

if (packets == 0)
bAlways = true;
else
bAlways = false;

if (protocol ==1){ //TCP Socket initilization
try {
addr = InetAddress.getByName(peer_addr);
TCPclient = new Socket(addr, port);
//OutputStream Out = TCPclient.getOutputStream();
System.out.println("OK create Socket and Outputstream");

}
catch (Exception e){
System.out.println("Cannot create Socket and outputstream");
}

}

else if (protocol == 2){ //UDP Socket initilization

try {
UDPsocket = new DatagramSocket();
addr = InetAddress.getByName(peer_addr);
UDPpacket = new DatagramPacket(mBuffer, packetsize, addr, port);
}
catch (Exception e) {
System.out.println("nthg out");
}
// UDPpacket.setLength(packetsize);
} // end of if (protocol == 2)

}

public void run() {
if (!bAlways) {

if (protocol ==1){ //TCP Socket initilization
try{
OutputStream Out = TCPclient.getOutputStream();
System.out.println("Success to get outputStream" );
}
catch (IOException e){System.out.println("Cannot get outputStream" );}


while ((packets > 0) && (bSend)) {
try
{
Out.write(mBuffer, 0, mBuffer.length);
packetSent++;
packets--;
System.out.println("OK to Write");

} catch (Exception e) {
packetSent--;
System.out.println("Cannot Write");
}

try {
Thread.sleep(rate);
}
catch (InterruptedException e) {}
}

}
else if (protocol == 2){ //UDP Socket initilization

while ((packets > 0) && (bSend)) {

//createPacket();
send();
packets--;
// System.out.println(seq);

try {
Thread.sleep(rate);
}
catch (InterruptedException e) {}
}
System.out.println("Yes Done");

}// end of if (protocol == 2)

}
else {

if (protocol ==1){ //TCP Socket initilization
//byte[] mBuffer = new byte[0];
try{
OutputStream Out = TCPclient.getOutputStream();
Out.write(mBuffer, 0, mBuffer.length);
System.out.println("Success to get outputStream" );
}
catch (IOException e)
{System.out.println("Cannot get outputStream" );}

while (bSend){
//try
//{
//Out.write(mBuffer, 0, mBuffer.length);
packetSent++;
System.out.println("OK to Write!!");
/*} catch (IOException e) {
packetSent++;
System.out.println("Cannot Write!! : "+ e);
}
*/
try {
Thread.sleep(rate);
}
catch (InterruptedException e) {}
}
}
else if (protocol == 2){ //UDP Socket initilization

while (bSend) {
//createPacket();
send();
// System.out.println(seq);
try {
Thread.sleep(rate); // in miniseconds
} catch (InterruptedException e) {}
}
System.out.println("UDP DONE!");

}// end of if (protocol == 2)
}

}

public void end() {
bSend = false;
if (protocol ==1){ //TCP Socket initilization
try{
Out.close();
TCPclient.close();
}catch (Exception e){
System.out.println(e);
}
}
else if (protocol == 2){ //UDP Socket initilization
try{
UDPsocket.disconnect();
UDPsocket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

private void send(){
try{
UDPsocket.send(UDPpacket);
packetSent++;
System.out.println("OK to send UDP datagram!!");
} catch (Exception e) {
packetSent--;
System.out.println(e);
}
}

/*
private void createPacket(){
seq++;
tempBuffer = Convert.toByte(seq);
mBuffer[0] = tempBuffer[0];
mBuffer[1] = tempBuffer[1];
mBuffer[2] = tempBuffer[2];
mBuffer[3] = tempBuffer[3];
UDPpacket.setData(mBuffer);
try{
// UDPpacket.setData(mBuffer);
} catch (Exception e) {
System.out.println(e);
}
}
*/

public int getNumOfPacketSent() {
return packetSent;
//return protocol;
}

public int getPacketSize() {
return packetsize;
}

}

==========================================================

/*
* ThreadRecv.java
*
* Created on April 2, 2003, 3:44 PM
*/

import java.util.*;
import java.net.*;
import java.lang.*;
import java.io.*;
/**
*
* @author ray
*/
public class ThreadRecv extends Thread {

private int seq;
private int rec_seq;
private int numPacketReceive;
private int numFailPacket;
private int packetsize; // in byte
private int port;
private DatagramSocket UDPsocket;
private DatagramPacket UDPpacket;
private ServerSocket TCPsocket;
private Socket TCPserver;
//private Socket socket;
private byte buffer[], mBuffer[];
private boolean bRecv;
private int protocol;
private InetAddress LocalAddr;
private InputStream In ;
private int i, offSet, length;
//private String RecvBuffer;

/** Creates a new instance of ThreadRecv */
public ThreadRecv(int packetsize, int port, int timeout, String local_addr, int protocol) {
bRecv = true;
this.port = port;
this.packetsize = packetsize;
this.protocol = protocol;
mBuffer = new byte[packetsize];
//mBuffer = new byte[65000];
seq = 0;

if (protocol ==1){ //TCP Socket initilization
try {
LocalAddr = InetAddress.getByName(local_addr);
TCPsocket = new ServerSocket(port, 10, LocalAddr);
}
catch (Exception e){
System.out.println(e);
}
}
else if (protocol == 2){ //UDP Socket initilization

try {
UDPsocket = new DatagramSocket(port);
//UDPpacket = new DatagramPacket(mBuffer,packetsize);
UDPpacket = new DatagramPacket(mBuffer, mBuffer.length);
//UDPsocket.setSoTimeout(timeout);
}
catch (Exception e) {
System.out.println(e + "Fail to construct Socket and Packet");
}
} //end of if (protocol == 2)
}

public void run() {
System.out.println("start receiving...");

if (protocol ==1){ //TCP Socket initilization
//Accept a new TCP connection
try {
TCPserver = TCPsocket.accept();
InputStream In = TCPserver.getInputStream();
System.out.println("Connection Accept Success ");
//The stream that receives the input from the connection.
}catch (Exception e) {
System.out.println("Connection Accept Failed: "+ e);
}
//while (bRecv){


int offSet = 0;
int length = -1;
buffer = new byte [4];

do{
try {
//offSet = 0;
System.out.println("Try receive!! "+length);
In.read(mBuffer, offSet, packetsize);
//length = In.read(buffer);
offSet += packetsize;
//if(length > 0)
// dataString += new String(buffer, 0, length);
System.out.println("Size of Packet received: "+length);
}
catch (Exception e){
System.out.println("TCP Receive Failed: ");
//disconnect();
//break;
}
numPacketReceive++;
//} while(length == packetsize);
} while(true);
}
else if (protocol == 2){ //UDP Socket initilization

while (bRecv){
receive();
}
}
System.out.println("Received 1 packet.");
}

public void receive(){
try{
UDPsocket.receive(UDPpacket);
System.out.println("Success to Receive UDP packet!!");
//UDPpacket.setLength(4);
//rec_seq = Convert.toInt(mBuffer);
// System.out.println("RECSEQ"+rec_seq);
//if (numPacketReceive == 0)
// seq = rec_seq;
//if (seq == rec_seq) {

// seq++;
//}
//else if (rec_seq != seq) {
// if(rec_seq>seq)
// numFailPacket = numFailPacket + (rec_seq - seq);
// seq = rec_seq+1;
//}
} catch (Exception e) {
//UDPsocket.disconnect();
//UDPsocket.close();
//System.out.println(e);
System.out.println("No Packet Received over 3 seconds");
}
numPacketReceive++;
}

public void end() {
bRecv = false;

if (protocol ==1){ //TCP Socket initilization

try{
In.close();
//TCPsocket.close();
TCPserver.close();

} catch (Exception e){
System.out.println("Fail to disconnected TCP: "+e);
}
}
else if (protocol == 2){ //UDP Socket initilization
try{
UDPsocket.disconnect();
UDPsocket.close();
} catch (Exception e) {
System.out.println("UDP disconnected");
}
}
}

public int getNumFailPacket() {
return numFailPacket;
}

public int getNumPacketReceive() {
return numPacketReceive;
}

public int getPacketSize() {
return packetsize;
}

}

 
Hello Wayne,

I see your new to Tek-Tips, welcome! [cheers]

Please follow this link: faq333-2924 to a FAQ about posting question and please take the time to read it, particularly item #13

-pete

 
Oh thanks for your notice,pete, perhaps I 'll summarize my problem in this manner!

When I run my program under these conditions:

try{
addr = InetAddress.getByName(peer_addr);
TCPclient = new Socket(addr, port);
OutputStream Out = TCPclient.getOutputStream();

Out.write(mBuffer, 0, mBuffer.length);
}
catch (IOException e)
{System.out.println(e);}

I get a runtime error on this line

Out.write(mBuffer, 0, mBuffer.length);

The error message is JAVA.IO.NullPointerException

The same thing happen in the case of reading data from the socket i.e. Runtime error at the line

In.read(mBuffer, offSet, packetsize);

with the same error message, where mBuffer is defined as

mBuffer = new byte[packetsize];

I don't know if there is anything wrong with my inputStream declaration :
LocalAddr = InetAddress.getByName(local_addr);
TCPsocket = new ServerSocket(port, 10, LocalAddr);
TCPserver = TCPsocket.accept();
InputStream In = TCPserver.getInputStream();

Could someone can help ?? Thanks for notice

 
Wayne,

I dont' see anything obvious in your code. Of course when you have a NullPointerException, something is "null" so in that line Out.write(mBuffer, 0, mBuffer.length); if that is the correct one, something is null yes?

I would check "Out" as well as "mBuffer" by stepping through the code in the debugger. If you don't have one you can do something like

System.out.println("Out is null " + (null == Out));

-pete

 
Thanks Pete,

I have try to debug the code and find that the NullPointerException is most likely incurred by the InputStream and OutputStream, Since I found that when I try to close them , the same error appears, It seems that I have something wrong with the declaration of the In (inputStream) and Out (outputStream) . But I cannot spot it out as I just actually follow the procedures decribed in my textbook to create an inputStream and outputStream for socket TCP communication. I really can't figure it out ... :<

Thanks for note anyway
 
One thing i just noticed is that you never call listen() for your Server socket. I've never executed code with out it so i don't have any idea what behavior would occur. I suppose it could be responsible for what you are seeing.

-pete

 
Thanks for the advice,
For the listen() method, I have checked with the text book and other sample codes, and found that the listen method is not implemented as well, it is explained that the bind() and listen() are being done during the construction of a ServerSocket, i.e. at the line :
TCPsocket = new ServerSocket(port, 10, LocalAddr);

Anyway, thanks for your notice , pete

Wayne
 
Hi

I just solve the problem , thanks Pete,
I found that in the output stream, I have to include the Out.write() statement in the same try () catch () with the construction of the outputstream , i.e.
OutputStream Out = TCPClient.getinputstream();
This is quite strange to me and make me trouble over the 2 days !!
the code is implemented in this way :

try{
OutputStream Out = TCPclient.getOutputStream();
while ((packets > 0) && (bSend)) {
try
{
Out.write(mBuffer);
packetSent++;
packets--;
System.out.println(&quot;OK to Write&quot;);

} catch (Exception e) {
packetSent--;
System.out.println(&quot;Cannot Write&quot;);
}

try {
Thread.sleep(rate);
}
catch (InterruptedException e) {}
}
System.out.println(&quot;Success to get outputStream&quot; );
}
catch (IOException e)
{System.out.println(&quot;Cannot get outputStream&quot; );}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top