Results 1 to 4 of 4
Thread: Extending java.net.Socket
- 06-10-2010, 04:27 AM #1
Member
- Join Date
- Dec 2008
- Posts
- 49
- Rep Power
- 0
Extending java.net.Socket
I'm trying to extend the Socket class to add two new methods, getName and setName, so that I can associate names with each socket. Everything compiles fine, but I get a client-side runtime error while attempting to connect to the server.
The problem occurs when ServerSocket.accept() returns a Socket for the connecting client, which I then have to downcast to my extended Socket class (called User) in the line "User client = (User) ss.accept();", where "ss" is the ServerSocket. I'm assuming that the Socket object isn't being cast into a User properly, causing the client to remain disconnected and throw the "socket not connected" error when it tries to establish I/O streams.
Is there any way I can fix this?Last edited by DC200; 06-10-2010 at 01:40 PM.
- 06-10-2010, 03:08 PM #2
You can't cast the value returned by accept() to your class. It is a Socket not a User object.Socket object isn't being cast into a User
OTMH Could you pass the Socket returned by accept() to the constructor of your class?
- 06-10-2010, 03:35 PM #3
Member
- Join Date
- Dec 2008
- Posts
- 49
- Rep Power
- 0
Only if that would allow me to perform the inherited Socket methods on a User object. The current User constructor simply calls to super(), so I just want a User object to be a Socket with two new methods that get and set a string (see code below).
Java Code:public class User extends Socket { String name; public User(String host, int port) { super(); } public void setName(String name) { this.name = name; } public String getName() { return name; } }
If I create a constructor which takes in a Socket, wouldn't I have to abandon super() and create a third method through which I would have to access the Socket? i.e. User.getSocket().getRemoteSocketAddress()?Last edited by DC200; 06-10-2010 at 03:38 PM.
- 06-10-2010, 04:23 PM #4
Similar Threads
-
Got confused with extending classes.
By nethz13 in forum New To JavaReplies: 7Last Post: 04-19-2010, 12:19 AM -
append response to the request from Socket and write to another socket
By vaibhav_singh_vs@yahoo.co in forum NetworkingReplies: 3Last Post: 04-17-2009, 07:02 PM -
Implementing and Extending together
By eva in forum New To JavaReplies: 2Last Post: 12-24-2007, 09:49 AM -
EXTENDING the string class
By ferno in forum New To JavaReplies: 3Last Post: 12-11-2007, 09:41 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks