Hi ive written some code to connect to a server through the use of a socket. Id like to write some simple code that allows me to send a string to the server, im assuming this will involve input and output streams but I am new to this. Ive put the code I am working with below, any insights into the best way to accomplish this would be great.
import java.net.*;
import java.io.*;
public class SocketMarket
{
public static void main(String [] args)
{
String serverName = "XX.X.X.XXX";
int port = XXXX;
try
{
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Connected to " + client.getRemoteSocketAddress());
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Thanks in advance
The above is how you would send just a
String, but you will probably want to build up some infrastructure around sending arbitrary text.The general idea is that your server and client will communicate with each other using
InputStream‘s andOutputStream‘s, which can be accessed from aSocketviagetInputStream()andgetOutputStream(), once the connection between them is made.For your server to receive connections, you should be using a
ServerSockettoaccept()incoming connections.