I think it is really strange problem because I don't even know where to start when repairing it.
My problem is my client don't receive message send from server.
I know I provided very little amount of code but I think other code really does not matter in this problem. If you want me to provide more code comment and I will send it to you.
Server code
String s = "";
for(String a : Main.users.keySet()) {
s = s + a + " ";
}
System.out.println("Sendind message: " + "SERVER USERS " + s);
output.writeBytes("SERVER USERS " + s);
output.flush();
System.out.println("User message sent");
Main.users.keySet() returns Set of strings.
Server console
SERVER USERS test
User message sent
Client code
System.out.println("TEST 1");
while(true){
try {
reader = new BufferedReader(new InputStreamReader(input));
line = reader.readLine();
System.out.println("TEST 2");
Client console
I/System.out: TEST 1
Related
DataInputStream dis = new DataInputStream(s.getInputStream());
String Message = dis.readUTF();
History.setText(History.getText()+ '\n' + "Client:-" + Message);
System.out.println("Message from client :- "+ Message);
}
catch(IOException e) {
History.setText(History.getText()+ "\n" + "Error in Connection");
History.setText(History.getText()+ "\n" + "Please Try Again or Exit");
Solved
Now able to get output from the client and the user
It appears that both the Client and Server are waiting for one to send a message to the other. Your code structure states that after the connection is made, the Server waits for a message from the Client,
DataInputStream dis = new DataInputStream(s.getInputStream());
String Message = dis.readUTF();
History.setText(History.getText()+ '\n' + "Client:-" + Message);
System.out.println("Message from client :- "+ Message);
And your Client is also waiting for a message from the Server,
DataInputStream dis = new DataInputStream(s.getInputStream());
String Message = dis.readUTF();
History.setText(History.getText()+ '\n' + "Server:- " + Message);
Remove either of those lines of code or have either the Client or the Server send a message to the other before waiting for an incoming message.
Your code is working.
In the action handler, you are clearing the Msg before sending it.
Msg.setText("");
Remove that line in the client and the server.
You still have problems, because only the first message can be received.
I have a program that includes HTTP connection to a PLM application that runs on SQL Server. The program is scheduled to run daily. It collects data from few sources, then issues a query to the PLM to store the data, and finally reads the PLM's reply to verify if the data was properly stored.
The application ran OK, until we upgraded both the DB (into SQL Server 2012) and the PLM.
Since then the upgrade, when the program establishes the connection it receives OK status; however, the data setting query does not affect the data base, and there is no answer received. There are no error messages - just malfunction.
My major question is - how to debug it. I know whet I send and what I receive. How can I get more data on what happens in between?
I attach the code for review. What I didn't add here is the query itself, which is WML-like string. The PLM should fire an answer regardless the query it receives, even if it is an error message. However, I get only NULL.
public Boolean amlArasCommunication (String data , int targetDbType, String passWord)
{
final String url = "http://plm-srv/InnovatorServer/Server/InnovatorServer2012.aspx";
final String schemeUrl = "'http://schemas.xmlsoap.org/soap/envelope/'";
String answer =””;
String dataBase = data base name;
Writer wout;
HttpURLConnection amlConnection = null;
try
{
// instantiate the HttpURLConnection with the URL object - A new connection is
// opened every time by calling the openConnection method of the protocol
// handler for this URL. This is the point where the connection is opened.
amlConnection = (HttpURLConnection) new URL(url).openConnection();
amlConnection.setDoOutput(true);
amlConnection.setDoInput(true);
amlConnection.setRequestMethod("POST");
amlConnection.setRequestProperty("SOAPAction", "ApplyAML");
amlConnection.setConnectTimeout(10000);
amlConnection.setReadTimeout(10000);
amlConnection.setRequestProperty("AUTHUSER", "Admin");
amlConnection.setRequestProperty("AUTHPASSWORD", calcMD5(passWord));
amlConnection.setRequestProperty("DATABASE", dataBase);
String query = "<?xml version='1.0'?>\r\n" +
"<SOAP-ENV:Envelope xmlns:SOAP-ENV=" + schemeUrl + ">\r\n" +
" <SOAP-ENV:Body>\r\n" +
data +
" </SOAP-ENV:Body>\r\n" +
"</SOAP-ENV:Envelope>\r\n";
// instantiate OutputStreamWriter using the output stream, returned from getOutputStream, that writes
// to this connection. If an I/O error occurs while creating the output stream, IOException will be fired.
wout = new OutputStreamWriter(amlConnection.getOutputStream());
wout.write (query);
wout.close();
// At this point, we've sent all the data. The outputStream was closed, while the connection is still open
int result;
if ((result = amlConnection.getResponseCode()) == HttpURLConnection.HTTP_OK)
{
// Get the communication results from the PLM
InputStream ac = amlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader (ac);
BufferedReader in = new BufferedReader(isr);
String readResult = in.readLine ();
int count = 0;
while (readResult != null)
{
answer += readResult + "\n";
readResult = in.readLine ();
count++;
}
in.close();
if (answer.contains("fault"))
System.out.println ("Error message: " + answer + "\nQuery: " + query);
else
log.message ("Lines count=" + count + "; com status=" + result + "; reply: " + answer, false);
}
else
// Error code is returned, or no status code is returned, do stuff in the else block
System.out.println("Connection failed with the following code: " + result);
}
catch (IOException e) { ; }
if (amlConnection != null)
amlConnection.disconnect ();
return true;
}
I think you will have to look into the log files of the PLM application to find out why you do not get an HTTP response. There might be a number of possible reasons why the application is not working anymore after the upgrade.
I guess that it will be difficult to debug the problem based on the client code only. As the server seems to accept your HTTP, I would expect that this event and errors would be written to a log file somewhere. You might also want to try some graphical tool like SOAP UI to test the SOAP service.
I have two applications, one written in Java and the other in C#. I am trying to send a string from the Java app to C# app.
My java code for sending the string is as follows:
String response;
try {
DataOutputStream outToServer =
new DataOutputStream(outGoingSocket.getOutputStream());
BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(outGoingSocket.getInputStream()));
outToServer.writeBytes(message + '\n');
outToServer.flush();
response = inFromServer.readLine();
System.out.println("Received: " + response);
} catch (Exception ex) {
System.err.println("Exception in incoming socket: " + ex.getMessage());
}
My C# code for receiving the data is as follows:
Byte[] bytes = new Byte[1000];
String data = null;
try {
Console.Write("Waiting for a connection... ");
TcpClient client = incomingSocket.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
int i;
while (true) {
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) {
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received:", data);
processReceivedMessage(data);
ackSocket(stream, "OK");
}
}
} catch (Exception ex) {
Console.WriteLine("Exception: ", ex);
}
I have a problem with receiving the data in the C# application. When I send the string "Data" in the Java app, and try to print the data received by the C# application using Console.WriteLine("Received: {0}", data), the output is:
Received: D
Received: ata
If I use Console.WriteLine("Received: ", data), the output is:
Received:
Received:
I want my C# application to receive the full string that is sent by the Java application. I tried to increase the buffer byte array size to 1000 but it doesn't help. I don't have experience using sockets, can someone show me what I did wrong?
So, as you can see, the receiving end picks up a response in chunks that might be considerably smaller than the total message.
You shouldn't be seeking to change this behaviour... it's a fact of network programming. It's your job to glue them back together again.
"I want my c# application receive the full string"
So, how is your receiving app meant to know that it has received the full string? Did you send a length field to indicate how much data is coming? Perhaps you expect \n to indicate the end of message? A zero byte?
If your terminator is indeed a newline, you might want to consider passing your NetworkStream to a StreamReader and calling ReadLine on it. Now, the StreamReader will keep reading from the stream until it hits a newline, then hand you the line.
I found this code to communicate with an IRC server (see below). However I did not find how to send a command to download or upload in xdcc.
Once connected to the IRC server and positioned in the channel. I want to send a command like.
/msg bot_name xdcc send #number_of_file
Thank you in advance for your answers, examples and help.
import java.io.*;
import java.net.*;
public class HackBot {
public static void main(String[] args) throws Exception {
// The server to connect to and our details.
String server = "irc.freenode.net";
String nick = "simple_bot";
String login = "simple_bot";
// The channel which the bot will join.
String channel = "#irchacks";
// Connect directly to the IRC server.
Socket socket = new Socket(server, 6667);
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream( )));
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream( )));
// Log on to the server.
writer.write("NICK " + nick + "\r\n");
writer.write("USER " + login + " 8 * : Java IRC Hacks Bot\r\n");
writer.flush( );
// Read lines from the server until it tells us we have connected.
String line = null;
while ((line = reader.readLine( )) != null) {
if (line.indexOf("004") >= 0) {
// We are now logged in.
break;
}
else if (line.indexOf("433") >= 0) {
System.out.println("Nickname is already in use.");
return;
}
}
// Join the channel.
writer.write("JOIN " + channel + "\r\n");
writer.flush( );
// Keep reading lines from the server.
while ((line = reader.readLine( )) != null) {
if (line.toUpperCase( ).startsWith("PING ")) {
// We must respond to PINGs to avoid being disconnected.
writer.write("PONG " + line.substring(5) + "\r\n");
writer.write("PRIVMSG " + channel + " :I got pinged!\r\n");
writer.flush( );
}
else {
// Print the raw line received by the bot.
System.out.println(line);
}
}
}
}
Your code shows only the minimum requirements needed to open a connection to a IRC server and keep it connected, actually the entire IRC protocol is much more complex and it is not implemented in the code.
The xdcc send is simply a normal IRC message sent privately to a specific other user (usually a bot) of the IRC server, therefore you can send it by using the command PRIVMSG:
writer.write("PRIVMSG " + botNickName + " :xdcc send #" + numberOfPack + "\r\n");
where botNickName and numberOfPack are two String variables containing the nickname of the bot (i.e. the recepient of the message) and the number (in string format) of the package in which you are interested.
Nevertheless you must consider that the DCC is an entire completely different protocol from the IRC protocol itself: it uses the CTCP message on IRC:
DCC SEND <filename> <ip> <port>
only to start a DCC session, but then there is the DCC protocol in order to manage the communication client-to-client. So if you really want to make the DCC works you should also implement it, but it would not be a quick job.
I asked a similar question in another thread but I think I'm just having trouble getting the syntax right at this point. I basically want to open a socket in Java, send a HTTP request message to get the header fields of a specific web page. My program looks like this so far:
String server = "www.w3.org";
int port = 80;
String uri = "/Protocols/rfc2616/rfc2616-sec5.html#sec5.1"
Socket socket = new Socket(server, port);
PrintStream output = new PrintStream(socket.getOutputStream());
BufferedReader socketInput = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output.println("HEAD " + uri + " HTTP/1.1");
//String response = "";
String line = "";
while((line = socketInput.readLine()) != null){
System.out.println(line);
}
socketInput.close();
socket.close();
It doesn't really work. Or it doesn't work for all websites. If someone could just tell me the immediate problems with what I'm doing, that would be great. Thank you!
Change
output.println("HEAD " + uri + " HTTP/1.1");
to
output.println("HEAD " + uri + " HTTP/1.1");
output.println("Host: " + server);
output.println();
You have to send the Host header because usually there are more than one virtual host on one IP address. If you use HTTP/1.0 it works without the Host header.
I would use some higher-level component, like HttpURLConnection (see here) or apache http components.