I’m new to Java, and I’m learning how to send messages via the Socket() class.
I’m trying to wrap my brain around how strings are sent and received between 2 simple chat programs. I’ve found plenty of examples online, for TCP/UDP chat clients and chat servers.
But I’m still confused with buffered data and strings.
In my code I added 3 fields (field1, field2, area), and a submit button with an event listener.
Below is part of the code, showing how I attached the listener and the class it instantiates.
......more code above this
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
new SendRequest();
}
});
public class SendRequest{
SendRequest(){
try{
String dip = field1.getText(); // ip address
String port = field2.getText(); // port num
int pnum = Integer.parseInt(port);
String mess = area.getText(); // large text box
Socket skt = new Socket(dip, pnum);
/* kinda not sure about this part, with strings */
}
catch(IOException io){
System.out.println("error? " + io.getMessage());
}
}
}
I’ve seen so many example online, that now I’m slightly more confused.
After instantiating the new Socket(), what’s a decent way to send multi-line text?
In the “kinda not sure part” create a PrintWriter using the OutputStream from the socket,
then to print the message call the PrintWriter’s print method on the “mess” String from your text area.
This puts the message string in the output stream buffer but isn’t sent till you call the PrintWriters flush method.
Finally close the PrintWriter.
The text should be sent multilined as the textareas string will have contain “\r\n” when you pressed enter.
Eg.