Send message using sockets and XMPP - java

I'm learning Java Sockets and want to try implement XMPP library using only Sockets, but I can't understand how to do it. I read RFC, but didn't understand anything.
I want to implement those features:
Send/receive messages
Status of users
All contacts
As I know this means that I can successfully proceed sending messages to the server, but HOW?
public static void main(String[] args) {
String connect = "<?xml version='1.0'?> "
+ "<stream:stream "
+ "to='jabber.ru' version='1.0' "
+ "xmlns='jabber:client' "
+ "xmlns:stream='http://etherx.jabber.org/streams'>";
String msg = "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">";
try {
InetAddress address = InetAddress.getByName(host);
Socket socket = new Socket(address, port);
socket.setKeepAlive(true);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(connect);
bw.flush();
System.out.println("Message sent to the server : " + connect);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " + message);
bw.write(msg);
bw.flush();
System.out.println("Message sent to the server : " + msg);
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
message = br.readLine();
System.out.println("Message received from the server : " + message);
} catch (Exception exception) {
exception.printStackTrace();
}
}
Note: I don't want to use any libraries! So Smack and others are not helpful.

After receiving the confirmation of the switch to TLS, you need to switch your socket to TLS and not use clear text anymore. When done, you can simply open the stream and start the negotiation sequence. The server will send your stream features and you will be able to authenticate.

Related

the buffer in server doesn't read the value that client sent

The client sends data (string) to the server, and the server must read it, but in my case the server didn't read the data (value) that the client sent, and I didn't know where is the problem exactly, because normally the steps to read data are all correct in the server side
Client side:
Socket socket = new Socket(address, authenticationServerPort);
username = username + "\n"; // to send username through socket without
String h=getUserInput();
// waiting
// Send the message to the server
// send public key
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
System.out.println(h);
bw.write(h);
bw.flush();
System.out.println("Message sent to the Authentication server : "+ h);
Server side:
Socket clientSocket = null;
try {
System.out.println("Server Running");
int serverPort = 8029; // the server port we are using
ServerSocket listenSocket = new ServerSocket(serverPort);
List<BlockChain> resultList = new ArrayList<BlockChain>();
while (true) {
clientSocket = listenSocket.accept();
InputStream is = clientSocket.getInputStream();
System.out.println(is);
InputStreamReader isr = new InputStreamReader(is);
System.out.println(isr);
BufferedReader br = new BufferedReader(isr);
String request = br.readLine();
System.out.println("the msg receving from client is : "+request);
PrintWriter out;
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())));
if (clientSocket != null) {
clientSocket.close();
}
}
catch (Exception e) {
e.printStackTrace();// TODO: handle exception
}
}
Someone tell me where is the problem exactly.

how to send TCP Requests in java

I am using Sockets to connect using TCP and I want to make different calls. e.g. Get InputValue
I have these type of different requests which I want to make from already running server.
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
String func="Get inputvalue";
byte[] tRequest = encoder.string2bytes(func);
out.write(tRequest);
out.flush();
System.out.println("write done");
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
It says it connected as just connected printout got printed. Write done print is also printed but no data is returned and the program keeps on running.
If I use telnet then this same request call returns data successfully.
So the question is how to make TCP calls in java?
Update: I solved this by:
PrintWriter toServer =
new PrintWriter(client.getOutputStream(),true);
BufferedReader fromServer =
new BufferedReader(
new InputStreamReader(client.getInputStream()));
toServer.println("Get inputvalue\r\n");
String line = "";
System.out.println("Client received: ");
while ((line = fromServer.readLine()) != null) {
System.out.println(line);
}
but the program keeps on running in the while loop and prints nothing. how to check that response is ended?

Client-Server communication with BufferedReader hanging

I'm testing around with client-server communication.
I have a server that should receive messages and print them, and send messages that it gets from System.in using a Socket. The client reads messages from the Socket, and sends back some messages. But for some reason both the server and the client get locked when checking if there is a message from the other end (at readLine()).
This client:
public void run() {
try {
Log.i("DataManager", "Trying to connect to server");
socket.connect(new InetSocketAddress(ADDRESS, PORT), 3000);
Log.i("DataManager", "Connected to: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
while (socket.isConnected()) {
if ((inputLine = in.readLine()).isEmpty()){
Log.i("DataManager", "Server says: " + inputLine);
}
synchronized (outcoming){
if (!outcoming.isEmpty()){
for (int i = 0; i < outcoming.size(); i++){
out.println(outcoming.get(i));
outcoming.remove(i);
}
}
}
}
}
...
}//
The Server:
ServerSocket listener = new ServerSocket(PORT);
try {
Socket socket;
socket = listener.accept(); //waits for connection
System.out.println("Client connected: " + socket.getInetAddress());
BufferedReader sysRead = new BufferedReader(new InputStreamReader(System.in));
BufferedReader clientIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true); //autoflush
String inputLine;
out.println("Hello, you are connected to server" + listener.getInetAddress());
while (true){
if ((inputLine = clientIn.readLine()).isEmpty()){
System.out.println("Client says: " + inputLine);
}
String line = sysRead.readLine();
if (line.equals("stop")){
break;
} else {
out.println(line);
}
}
socket.close();
}
I tried solving this by encasing the readLine statements with if(in.ready()) but it didn't help at all. I've been looking around on google and found that this is caused by the fact that readLine() looks for eof, and the stream from the socket only ends when the socket is disconnected. I have no idea how to get around this problem other that writing some kind of protocol where i end my messages with a specific sequence. Is there a better way around this problem?

Send string to client upon command JAVA

So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break

Simple Java Chat Program Help, Client Timesout when Connecting With Server

I'm creating a very simple Java chat program, using the Java TCP sockets. I'm new to socket programming and Java. I cannot connect with server, because every time the client connects to server it times out. Maybe, it is because I'm typing the wrong IP address——I don't know.
Here is the code for the Server:
try
{
int fport = Integer.valueOf(port.getText());
ServerSocket server = new ServerSocket(fport);
Socket socket = server.accept();
msg.append("\\n Server is listening to port:" + port.getText());
BufferedReader input = new BufferedReader( new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.print(msgtxt.getText());
msg.append("\n\n" + input.readLine());
msg.append("\n\n" + Nombre.getText() + msgtxt.getText());
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error:" + ex.getMessage());
}
Here is the code for the Client:
try
{
int iport = Integer.valueOf(port.getText());
int i1;
int i2;
int i3;
int i4;
i1 = Integer.valueOf(ip.getText());
i2 = Integer.valueOf(ip1.getText());
i3 = Integer.valueOf(ip2.getText());
i4 = Integer.valueOf(ip3.getText());
byte[] b = new byte[] {(byte)i1, (byte)i2, (byte)i3, (byte)i4 };
InetAddress ipaddr = InetAddress.getByAddress(b);
Socket sock = new Socket(ipaddr, iport);
BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
output.write(m.getText());
while(!input.ready()){}
msg.setText("\n\n" + input.readLine());
msg.setText("\n\n" + m.getText());
output.close();
input.close();
}
catch (Exception ex)
{
msg.setText("\n\n" + "Error: " + ex.getMessage());
}
verify that you can connect to the server using telnet (on windows you may need to install it as it's not installed by default anymore).
basically, open a connection to your server and see that it works:
telnet host port
if it works, maybe the problem is not in establising the connection but in waiting for a response from the server (add the exception to your question).
one note:
you can open a socket without creating the INetAddress as you did, just new Socket(hostname, port).

Categories