Hello, i m creating connection oriented server/client(TCP) socket.i have created whole server socket and i have written packet on server socket successfully and i have created client socket also but i m not be able to read packet so please give me the idea about read the packet(code or example) on client socket and tell clearly that can i read a packet on client socket or not if no then what should use in place of client and server socket
views:
41answers:
2
A:
You don't generally read a packet at a time - you read from the InputStream
returned by Socket.getInputStream()
. You should almost certainly be treating the connection as a stream, rather than even attempting to handle individual packets.
If you still run into problems, it would really help if you could post some code to show how you're connecting the socket etc.
Jon Skeet
2010-09-08 06:27:49
A:
I had to implement such a thing for my networking course in college.
Here's an excerpt from the book
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println("Received: " + clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
}
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Hopefully this will be sufficient to figure out what you did wrong. Good luck!
Sanchit
2010-09-08 06:35:58