InetAddress.getByAddress(byte[]) problem...
the following line of code is not compiling for me.
InetAddress inAd = InetAddress.getByAddress(IAbyte);where IAbyte is an byte array of length 4 where each byte is the component of an IP address.
I am recieving the error:
C:\tmp\FTPServer,java.java:507: cannot resolve symbol
symbol : method getByAddress (byte[])
location: class java.net.InetAddress
InetAddress inAd = InetAddress.getByAddress(IAbyte);
Which is quite odd as the API http://java.sun.com/j2se/1.4.1/docs/api/java/net/InetAddress.html#getByAddress(byte[]) says that the method should be there.
Knowing me it is just a silly little error on my part ^_^;
Which is quite odd as the API http://java.sun.com/j2se/1.4.1/docs/api/java/net/InetAddress.html#getByAddress(byte[]) says that the method should be there.
yes its right
by the way which version of jdk r u using ...
Similar Messages
-
Byte size problem - InetAddress.getByAddress()
Hi,
I'm trying to use the InetAddress class, but cannot put certain IP addresses into it. The reason for this is that I have a string containing my IP address, which I break down using the string tokenizer to give 4 numbers, each between 0 and 255, which I then convert to an array of bytes, in order to use the getByAddress method.
The problem is that bytes go from -128 to 127 - rather than from 0 to 255. How am I supposed to use this method for IP addresses where one (or more) of the numbers is over 127?
Cheers,
JohnAhh - cheers,
I thought that getByName refered to the actual name - i.e. "localhost".
Do you know if there is a method which will resolve this hostname from an IP address?
(i.e. in the same way as adding "-a" to a ping resolves the hostname?)
Thanks again,
John -
Base64Binary to byte[] problem in Wireless Toolkit and NetBeans
Hi,
I am generating stub with J2me Wireless toolkit. But the problem is that the toolkit can't successfully convert base64Binary to byte[] and gives error "Unknown simple type byte[]". Netbeans also gives some error while compiling it. Please anybody tell me how can i resolve this problem. Using base64Binary type is must.
Kindly reply if you know. My email address is [email protected]
Wasif Ehsan
[email protected]public interface JobUpdate {
@SuppressWarnings("unchecked")
public String[] getUpdatedJobList(@WebParam(name="phoneJobs")String[] phoneJobs);
@SuppressWarnings("unchecked")
public void retrieveJobsWorked(@WebParam(name="data")byte [] data);
I then use this to start the service
JobUpdateImpl implementor = new JobUpdateImpl();
JaxWsServerFactoryBean svrFactory = new JaxWsServerFactoryBean();
svrFactory.setServiceClass(JobUpdate.class);
svrFactory.setAddress("http://localhost:9000/JobUpdate");
svrFactory.setServiceBean(implementor);
svrFactory.getInInterceptors().add(new LoggingInInterceptor());
svrFactory.getOutInterceptors().add(new LoggingOutInterceptor());
svrFactory.create();
Then use the wtk stub generator pointing at the service.
http://localhost:9000/JobUpdate?wsdl
The error returned by the tool is error: Found unknown simple type: byte[]
Any ideas? -
Hello!
I'm trying to send data between to computer using RS232.
The problem I encounter is the following:
when I send data from 0 to 127 they are well received.
from 128 to 160 they are bad received (actually 130 is received as 8218, 131 as 405, 135 as 8225).
from 160 to 255 they are well received.
I know that bytes in Java are from -128 to +127 and I could understand that number greater than 127 have problems to be transmitted, but because of those 160 to 255 numbers that are well received, I don't get it.
I tried to find a pattern with the association of number sent and received between 128 and 160 but I didn't find anything relevant...
I'm using a simple RS232 cable via an USB to RS232 converter on my computer (I don't have any serial port) while the other computer is directly using its RS232 port.
The port is configured to send data to 9,6kbps, no parity bits, 1 stop bit and 8 data bits.
Has anyone any idea of where my problem could come from?
I get really confused with that...
By the way, if some admins wants to put my post somewhere else because here is not the appropriate place, I totally understand it but could he (or she?) just mail to tell me where it has been put, because last time I posted I didn't find it anymore... lol
Thanks ;)Please help me!
finally I cannot even write a conversion algorithm because different values return the same value (sounds odd but here it is:)
Send Receive
127 127
128 8364
129 65533
130 8218
131 402
132 8222
133 8230
134 8224
135 8225
136 710
137 8240
138 352
139 8249
140 338
141 65533
142 381
143 65533
144 65533
145 8216
146 8217
147 8220
148 8221
149 8226
150 8211
151 8212
152 732
153 8482
154 353
155 8250
156 339
157 65533
158 382
159 376
160 160
As you can see for example 143 and 144 both return 65533...
What can I do? -
A little byte[] problem
Hi,
I'm facing an unusual problem with creating an array of byte arrays, ie byte[][].
Below is my test code to create this array and read it back. For some reason this is not working. I'll definitely use some knowledge here. Thanks
import java.io.*;
public class Test {
static byte[][] testbyte = new byte[10][3];
public static void main(String[] args) {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
for(int m=0;m<3;m++){
for (int i = 0; i < 10; i++) {
dout.writeInt(i*m);
testbyte[m]=bout.toByteArray();
for(int index=0;index<3;index++){
ByteArrayInputStream bin = new ByteArrayInputStream(testbyte[index]);
DataInputStream din = new DataInputStream(bin);
int m = 0;
while (m < 10) {
System.out.println(din.readInt());
m++;
catch (IOException ex) {
System.out.println(ex);
}Actually I send one row of data at a time - thatis
ony 8bytes * 4 = 32 bytes. If you are only send 4 doubles at a time, do you
need to keep all the previous values.
Sending 32 bytes every 10 ms should not be a
problem.
To do this I use DatagramPacket with an offset onthe byte array which
increments by 32 and a length of 32 bytes. If the byte array only contained the data you need to
send this would much simpler.
Note, toByteArray() creates a new byteArray copy of
the data in the ByteArrayOutputStream so it could be
copying around alot of data you don't need.I call toByteArray() only once. After the array is created I do something like DatagramPacket packet = new DatagramPacket(myByteArray,offset,length,address,port)
I'll try tcp as well though I anticipate the speedwill be much lower.
If you keep the socket connection open, then the
speed will be the same, except it will also be much
more reliable. Only the connection latency is slower.
However on a LAN this should less than 0.3 ms once
off.I'll definitely try this. Thanks for the headsup on the reason for the tcp latency. I though each send-receive transaction had to be ack'ed. -
Type byte problem !!!
private DatagramPacket receivePacket;
private DatagramSocket socket;
public class receive {
public receive() {
try {
socket = new DatagramSocket( 1002 );
catch( SocketException se ) {
se.printStackTrace();
System.exit( 1 );
public void waitForPackets() {
while ( true ) {
try {
byte data[] = new byte[ 2048 ];
receivePacket = new DatagramPacket(
data, data.length );
socket.receive( receivePacket );
catch( IOException exception ){
System.out.print(
exception.toString() + "\n" );
exception.printStackTrace();
add watch the byte data[] found that
some data[] such as data[1] data[7]
over 8 bit and neg value occured
why ? help me !
data: byte[2048] = {...}
data[0]: byte = 0x0
data[1]: byte = 0xffffff87
data[2]: byte = 0x36
data[3]: byte = 0x0
data[4]: byte = 0x0
data[5]: byte = 0x4
data[6]: byte = 0x1
data[7]: byte = 0xffffff9c
data[8]: byte = 0x3
data[9]: byte = 0x24
data[10]: byte = 0xffffff80
data[11]: byte = 0x16
data[12]: byte = 0x58
data[13]: byte = 0x4e
data[14]: byte = 0x2i manage to walkaround the problem...
just in case someone is interested:
i convert the image to greyscale using colorspace instead of defining the BufferedImage to bt of TYPE_BYTE_GRAY.
Here's the code:
image = ImageIO.read(file);
bI = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
pic = bI.createGraphics();
pic.drawImage(image, 0, 0, null);
pic.dispose();
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
bI = op.filter(bI, null);
i = new ImageIcon(Toolkit.getDefaultToolkit().createImage(bI.getSource()));
b1 = new JButton("ColorSpace", i);
frame.getContentPane().add(b1); -
Simple string / bytes problem
Hi
I'm basically trying to simulate DES in java from scratch (so no use of existing API's or anything). I've got a basic idea of how DES works (use of a feistel cipher).
So to start off I'm trying to get the bytes of a string with this simple program:
public class Test {
public static void main(String[] args) {
String testString = "hello";
System.out.println(testString.getBytes());
}The output consists of some characters (namely numbers, letters and 1 special character).
But when I change the variable testString to some other String, complie and run I still get the same output even though the String is different. Also why are there 9 characters for a String thats only 5 characters long?
ThanksWhen you use System.out.println( something ) it uses to the toString() method of the object referenced by 'something'. When the something is an array such as an array of bytes the toString() methed returns a pseudo reference to the array which in no way reflects the content of the array.
If you just want to see the content of the array then use Arrays.toString(something) to generate a String representation of the content of the array.
Also, the use of String.getBytes() will convert the String to bytes using your default character encoding. This is rarely what you want since the result may depend on which platform you are working on. In my view, the safest and best approach is to explicitly define the encoding and since it will encode ALL characters one can throw at it I always use utf-8. So, to convert a String to bytes I would usebyte[] bytesOfString = "your string".getBytes("utf-8");and to convert them back to a String I would useString yourString = new String(bytesOfString,"utf-8");One final point, do not assume that an apparently random array of bytes such as one gets from DES encryption can be converted to a String using the above. In general it can't because not all bytes and byte sequences are valid for a particular character encoding. If you absolutely have to have a String representation then you should encode (not encrypt) the bytes using something like Base64 or Hex encoding.
Edited by: sabre150 on Jan 27, 2008 3:04 PM -
Extra bytes problem with audio capture,j2me
hi there
I m working on a J2ME application that captures live audio through microphone into a bytearrayoutputstream .
i have supplied the capture time,sampling rate, bits per sample, no of channels info to the program.
but when i check out the size of the byte array , i see that its greater than what it should be !!!
if the size had been lesser than expected, i could guess that sum bytes are getting lost , but what attributes to the larger size.
and everytime i run the program i c that the size is larger than expected though the number by which it exceeds is different everytime.
can ne one help??Hi,
Thank you very much for your help. I changed the code as you suggested. It minimizes the gap, but there is still part of missing voices.
When you tried it, did you get really perfect (no gap) recording, as if it was recorded to one single stream?
below is my recording code:
for(int i=0;i<types.length;i++) {
rc.setRecordStream(baos);
rc.startRecord();
Thread.sleep(2000);
rc.stopRecord();
rc.commit();
init.append("baos size after rec:" + baos[i].size()+"\n");
}//end of for
p.stop();
p.close();
and here is the code for playing back the voice:
for(int i=0;i<3;i++) {
bais[i] = new ByteArrayInputStream(baos.toByteArray());
try {
p = Manager.createPlayer(bais[i],types[i]);
p.prefetch();
p.start();
Thread.sleep(p.getDuration());
p.stop();
p.close();
catch(Exception e) {
init.append("exception in playing back voice: "+e.toString()+"\n");
e.printStackTrace();
for playing back, we need to stop and close the player first, then create a new player to play the next input stream, dont we?
Thanks
- alfo -
Send a request using Http(s)URLConnection through proxy issue
Hi all,
Here are system environment,
OS: Ubuntu 12.04
Java version: 1.6.0_27
OpenJDK Runtime Environment (IcedTea6 1.12.4) (6b27-1.12.4-1ubuntu1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)
There are 3 roles introduction as below:
1. A https client: It can not direct connect to https server. Because it is restricted in a enclosed network environment just like intranet(ip is 10.100.11.8).The only way out is proxy server.
2. A proxy server: Locate between https client and https server. It have two network interfaces(ip are 10.100.11.10 and 192.168.11.10)
3. A https server: It is on extranet(ip is 192.168.11.123) and it also cannot connect to https client directly.
The other network environment setup is: There is no DNS server on https client network environment.
The following is part of https client code section:
public static void main(String args[]){
String proxyIp ="10.100.11.10";// proxy server IP
testConn(proxyIp);
private static void testConn(String proxyIp){
String httpsURL="https://192.168.11.123:8443/httpsServices";
setSSLContext();// I thought this is not root cause so I do not post on
try{
InetAddress intIPAdd= InetAddress.getByAddress(convStrToByte(proxyIp));
InetSocketAddress proxyInetAddr = new InetSocketAddress(intIPAdd,80);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyInetAddr);
URL httpsUrl = new URL(httpsURL);
HttpsURLConnection httpsCon = (HttpsURLConnection) httpsUrl.openConnection(proxy);
httpsCon.setDoOutput(true);
httpsCon.setDoInput(true);
httpsCon.setRequestMethod("POST");
httpsCon.setDefaultUseCaches(true);
httpsCon.setUseCaches(true);
System.out.println("Get OutPutStream start!");
OutputStream out = httpsCon.getOutputStream(); // or httpsCon.connect();
System.out.println("Get OutPutStream done!");
OutputStreamWriter owriter = new OutputStreamWriter(out);
owriter.write("<request>test</request>");
owriter.flush();
owriter.close();
private static byte[] convStrToByte(String ip){
String str[] = ip.split("\\.");
byte[] ipAry = new byte[str.length];
for(int i=0;i<str.length;i++){
ipAry[i] = (byte) Integer.parseInt(str, 10);
return ipAry;
All right, my problem is, while print out "Get OutPutStream start" untill "Get OutPutStream done", it always takes about 5 secs.
No Error or exception. It was just hanging there approx 5 secs.
I observed the packets flow with wireshark.
Found out that hang time is to send a multicast to ask MDNS the proxy IP. No one reply this message. It would ask 3 times and then send request to proxy.
About https trust and authentication issue. I use *All Trust* solution. because https server use self-signed CA by myself.
If need, I would update this post with code section of setSSLContext() part.
I wondering to know that I create proxy object using *InetSocketAddress(InetAddress addr, int port)*, or I create proxy ip instance using *public static InetAddress getByAddress(byte[] addr)* why it would ask to MDNS for proxy ip?
On normal concept, I give an ip address and it do not need to resolve this ip for domain name.
Check InetAddress getByAddress(byte[] addr) of JAVA SE6 API:
It says: 'This method doesn't block, i.e. no reverse name service lookup is performed.'
What can I do to let https client don't need to ask MDNS?
Thank you guys so much.
Edited by: 1002346 on 2013/4/29 上午 12:05Java does reverse DNS lookups for security reasons. Not sure you can disable it but if you can it will be described on the Networking Properties page.
-
How to bind DatagramSocket to second NIC?
I need to bind a DatagramSocket to a second "IPv6-enabled" NIC. Binding to the main "IPv4" NIC works fine but I'm being incapable to change to a different NIC. These are my network settings:
eth0 Link encap:Ethernet HWaddr 00:11:43:c8:bd:1c
inet addr:192.168.1.17 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::211:43ff:fec8:bd1c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:3118 errors:0 dropped:0 overruns:0 frame:0
TX packets:2608 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3422763 (3.4 MB) TX bytes:317046 (317.0 KB)
Interrupt:16
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:12 errors:0 dropped:0 overruns:0 frame:0
TX packets:12 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:720 (720.0 B) TX bytes:720 (720.0 B)
tun0 Link encap:UNSPEC HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
inet addr:127.0.1.1 P-t-P:127.0.1.1 Mask:255.255.255.255
inet6 addr: aaaa::1/64 Scope:Global
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:500
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)I want my DatagramSocket to binded to tun0 so I've tried with
DatagramSocket mySocket = new DatagramSocket(port, InetAddress.getByName("127.0.1.1"));and
DatagramSocket mySocket = new DatagramSocket(port, InetAddress.getByName("aaaa::1"));but none of the above methods work: my application is not receiving any UDP traffic on the tun0 interface, at the port specified. I think that binding to a secondary NIC is more complicated than I thought (-:
Any help is welcome !! Thanks !!
Daniel.Try that method instead getByName and see if you have better luck, keep in mind what the method documentation says about ipv6 addresses.
getByAddress
public static InetAddress getByAddress(byte[] addr)
throws UnknownHostException
Returns an InetAddress object given the raw IP address . The argument is in network byte order: the highest order byte of the address is in getAddress()[0].
This method doesn't block, i.e. no reverse name service lookup is performed.
IPv4 address byte array must be 4 bytes long and IPv6 byte array must be 16 bytes long
Parameters:
addr - the raw IP address in network byte order
Returns:
an InetAddress object created from the raw IP address.
Throws:
UnknownHostException - if IP address is of illegal length
Since:
1.4This is from the sun api for Java 6 btw. [http://java.sun.com/javase/6/docs/api/] -
How to query transmitter's hostname?
Hi,
One way to query the transmitter's hostname and port number is to use SessionAddress + RTPManager + Participant (e.g. in the AVReceive2 example).
However, I use Manager + Player in my "receiver" program (snippet below). How do I query the transmitter's hostname and port number from the Manager or Player?
------snip------
MediaLocator inputLocator = new MediaLocator("rtp://host:port/video");
player = Manager.createPlayer(inputLocator);
player.addControllerListener((ControllerListener)this);
player.start();
------snip------
cheers,
RachgetRemainder()
public java.lang.String getRemainder()Get the MediaLocator string with the protocol removed.
Returns: The argument string.
Use this method to get the string and parse it to get raw IP address(byte[]) and port.
static InetAddress getByAddress(byte[] addr)
- Returns an InetAddress object given the raw IP address
This method should be called on with the raw IP address to get an InetAddress and then getHostName() can be called on the returned InetAddress object.
(InetAddress.getByAddress(raw IP address)).getHostName() --> HOSTNAME
And for this the name service should be properly configured on your system. -
I don't understand this, but I suppose the solution is simple.
I wanna use the getByAddress(byte[] address) method of the class InetAddress in java.net .
address is a byte array of length 4, that should contain the 4 parts of an IP address.
BUT, each part of an IP address can be 32 bits long, wich is bigger then the possible length of a byte.
Someone knows what I do wrong?I don't understand this, but I suppose the solution
is simple.
I wanna use the getByAddress(byte[] address) method
of the class InetAddress in java.net .
address is a byte array of length 4, that should
contain the 4 parts of an IP address.
BUT, each part of an IP address can be 32 bits long,
wich is bigger then the possible length of a byte.
Someone knows what I do wrong?Hi, it depends on which type of ip-address. The one which is most common is only 32 bits long. E.g. 255.123.123.01 <- 4 bytes.
Kaj -
Problem with socket communications
I am trying to put together a client server socket communication pair.
I have one application that runs in the background acting as a server and another that can be started and stopped that acts as a client.
I can start the server and create a server socket with no problem.
I can start the client and it connects to the server.
The server acknowledges the connection and appears to go into a blocking state waiting for the client to send another message.
The server blocks at the line
parent.logit("Waiting for message from EVR..... ");
The problem is that when the client sends another message, the server doesn't hear it.
I am not sure if the problem is with the client or server communication code.
If anyone out there is a socket communication guru, I would appreciate it if you could tell me what I am doing wrong.
Thanks
Server code:
import java.io.*;
import java.net.*;
public class EVRServer
extends Thread
EVRDataLoader parent = null;
ServerSocket serverSock = null;
Socket clientSock = null;
BufferedReader reader = null;
BufferedWriter writer = null;
int evrPort = 0;
int retryLimit = 10;
int retryCount = 0;
boolean alive = false;
boolean killSocket = false;
boolean evrConnected = false;
boolean retry = true;
EVRListener evrListener = null;
//=============================================================================
// Full constructor
//=============================================================================
* Full constructor.
* @param dl DataLoader - Parent application
* @param port int Socket port
public EVRServer(EVRDataLoader dl, int port)
parent = dl;
evrPort = port;
//=============================================================================
// Run method - Main thread executed by start() method
//=============================================================================
* Main thread executed by start() method
public void run()
while (retry)
if (retryCount > retryLimit)
retry = false;
parent.logit("Retry count = " + retryCount);
// Create new server socket connection
if (serverSock == null)
try
serverSock = new ServerSocket(evrPort);
parent.logit("Created Server Socket for EVR on port " + evrPort);
alive = true;
killSocket = false;
evrConnected = false;
catch (Exception e)
parent.logit(
"ERROR - Could not create Server socket connection for EVR: " +
e.toString());
killSocket = true;
alive = false;
// Create new client socket connection
if (clientSock == null)
try
parent.logit("Waiting for EVR to connect");
clientSock = null;
clientSock = serverSock.accept();
retryCount = 0;
evrConnected = true;
killSocket = false;
parent.logit("EVR connected on server Socket Port " + evrPort);
catch (Exception e)
parent.logit("ERROR - Error accepting EVR connection: " + e.toString());
killSocket = true;
try
reader = new BufferedReader(new InputStreamReader(
clientSock.getInputStream()));
writer = new BufferedWriter(new OutputStreamWriter(
clientSock.getOutputStream()));
parent.logit( "Created reader "+reader);
parent.logit( "Created writer "+writer);
catch (Exception e)
parent.logit(
"ERROR - creating reader or writer to EVR: " + e.toString());
killSocket = true;
int nullCount = 0;
while (killSocket == false)
try
parent.logit("Waiting for message from EVR..... ");
// sendMessage("Data Controller connected on port " + evrPort);
String s = reader.readLine();
parent.logit("EVR - Received message: " + s);
if (s != null)
parent.processEvrMessage( s);
else
sleep(1000);
nullCount++;
if (nullCount > 10)
parent.logit("Exceeded retry limit: ");
killSocket = true;
catch (Exception ex)
parent.logit("Error Reading from EVR: " + ex.toString());
killSocket = true;
parent.logit( "After while loop");
evrConnected = false;
try
retryCount++;
parent.logit("Closing EVR connection. ");
reader.close();
writer.close();
clientSock.close();
writer = null;
reader = null;
clientSock = null;
try
sleep(1000);
catch (Exception ee)
parent.logit("Error after sleep " + ee.toString());
catch (Exception e)
parent.logit("Error closing EVR server socket");
//=============================================================================
// Call this method to kill the client socket connection.
//=============================================================================
* Call this method to kill the client socket connection.
public void killConnection()
killSocket = true;
//=============================================================================
// Return RTM connected state
//=============================================================================
* Return RTM connected state
* @return boolean - Returns true if RTM is connected to server, false if not.
public boolean isRtmConnected()
return evrConnected;
//=============================================================================
// Returns state of server socket.
//=============================================================================
* Returns state of server socket.
* @return boolean - Returns true if server socket is enabled, false if not.
public boolean isServerSocketAlive()
return alive;
//=============================================================================
// Send a message to the client socket.
//=============================================================================
* Send a message to the client socket.
* @param msg String - Message to send.
* @return boolean - Returns true if message sent OK, false if not.
public boolean sendMessage(String msg)
parent.logit(" In EVR Server - Send Message - got message: " + msg);
if (evrConnected)
try
parent.logit("Sending message to EVR: " + msg);
writer.write(msg + "\n");
writer.flush();
return true;
catch (Exception e)
parent.logit("ERROR - Error sending message to EVR: " + e.toString());
return false;
else
parent.logit("EVR not connected, cannot send message: " + msg);
return false;
}Client code:
package evrsimulator;
import java.net.*;
import java.io.*;
class PortConnector
extends Thread
ServerSocket serverSock = null;
boolean isIP = false;
InetAddress addr = null;
Frame1 parent = null;
byte[] rawIP;
// String initialMsg = "";
public PortConnector( Frame1 f )
parent = f;
// This method is called when the thread runs
public void run()
if ( parent.hostName.indexOf( "." ) > 0 )
isIP = true;
byte[] rawIP = parent.getRawIP( parent.hostName );
try
System.out.println( "Connecting to host " +
parent.hostName + " on port " +
parent.socketPort );
if ( isIP )
addr = InetAddress.getByAddress( rawIP );
else
addr = InetAddress.getByName( parent.hostName );
System.out.println( "Inet address = " + addr );
SocketAddress sockaddr =
new InetSocketAddress( addr, parent.socketPort );
// Create an unbound socket
parent.client = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
parent.client.connect( sockaddr, parent.socketTimeOut );
parent.socketOut =
new BufferedWriter( new OutputStreamWriter(
parent.client.getOutputStream() ) );
parent.socketIn = new BufferedReader( new InputStreamReader(
parent.client.getInputStream() ) );
parent.localName = parent.localName +
parent.client;
System.out.println( "Parent socketOut = "+parent.socketOut);
System.out.println( "Parent socketIn = "+parent.socketIn);
catch ( UnknownHostException uhe )
System.out.println( "Unknown Host - " + uhe.getMessage() );
catch ( SocketTimeoutException ste )
System.out.println( "Socket time out - " + ste.getMessage());
catch ( IOException ioe )
System.out.println( "IO exception - " + ioe.getMessage() );
// Listen on socket for message from host - thread should block.
parent.portConnected = true;
while ( parent.portConnected )
try
String msg = parent.socketIn.readLine();
System.out.println( "Message from Host: " + msg );
System.out.println( "Message from Host: |" + msg + "|" );
if( msg.length() > 2)parent.processMessage( msg );
catch ( IOException ioe )
System.out.println( "Exception creating server socket." );
try
System.out.println(
"PortConnection - Closing socket and IO connections" );
parent.socketIn.close();
parent.socketOut.close();
parent.client.close();
parent.clockRunning = false;
if( parent.heartBeating) heartBeat.interrupt();
catch ( IOException ioex )
System.out.println( "Exception closing socket." );
}Your first problem is that you keep closing and recreating the ServerSocket. Do this once only in the lifetime of the server.
This is such a basic error that I haven't read the rest of the code. Before you go any further I suggest you read the Custom Networking trail of the Java Tutorial. -
Problem with socket connections through a proxy server.
People,
I set the system properties to use a proxy server so my application can fetch data from servers located outside my local network:
System.setProperty("socksProxyPort", port);
System.setProperty("socksProxyHost", proxy_addy);Then, when I attempt to stabilish a connection:
s = new Socket(this.getHost(), port);It hangs.
I appreciate any help since my available Java documentation is quite obscure regarding proxy servers.Is the proxy on another machine? Try it's IP. If
not, replace 'proxy' with 'localhost'.
- SaishYes, it is another machine.
byte x[] = {(byte)aaa,(byte)bbb,(byte)ccc,(byte)ddd};
s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(InetAddress.getByAddress(x), 8080)));
s.connect(new InetSocketAddress(this.getHost(), port));Again, it hung. -
Converting from a string to InetAddress
I am reading in a file that contains a line of text, for example:
192.168.5.2 young
This line is read in and split up by a string tokenizer. How can I convert the string IP address that is read in as the first token to an actual InetAddress that can be used in network communication.I am reading in a file that contains a line of text,
for example:
192.168.5.2 young
This line is read in and split up by a string
tokenizer. How can I convert the string IP address
that is read in as the first token to an actual
InetAddress that can be used in network communication.This code should help you
byte[] b=new byte[4];
//how u use getByName
InetAddress ob1=InetAddress.getByName("abc.xyz.com");
//how u use getByAddress
b[0]=new Integer(10).byteValue();
b[1]=new Integer(200).byteValue();
b[2]=new Integer(81).byteValue();
b[3]=new Integer(249).byteValue();
InetAddress ob2=InetAddress.getByAddress(b);
Maybe you are looking for
-
How to export Date book and Address book from Palm Desktop to Apple iCal and Address Book?
I have my calendar information and addresses stored in Palm Desktop date book and address book, respectively. I am running Palm Desktop 4.2.1. Everytime I try to export the date book or address book to my desktop using the vCal format, the Palm deskt
-
I'm having some trouble trying to figure out how this event listener will work. The main application is building an arrayCollection of a calendarDay custom components which is displayed by a DataGroup. Within each calendarDay custom component i may c
-
SOA Humantask :Faulted while invoking operation "initiateTask" on provider "TaskService"
Hi, iam new to Oracle SOA humanask, Iam migrating SOA 10.1.1.3 to SOA 11.1.1.7. After migration of BPEL Humantask process,iam getting "Faulted while invoking operation "initiateTask" on provider "TaskService" in audit trail as below. Can you please s
-
Internal error - access to IT_ADR2_L when adding E1BPADTEL/SMTP segments (i
When Syndicating Customer Master Data from MDM to ECC (using an iDOC), I receive the following error.... Internal error - access to IT_ADR2_L when adding data in E1BPADTEL and E1BPADSMTP segments (in E1ADRMAS). Has anyone received this error? Thanks
-
I cannot as of recent click and drag anything to my workspace, (ex: dragging a plug in over onto a solid) or taking an imported jpeg and dragging it down to where layers are?? I also cannot re-arrange my layer order. What did I change or do causing