String based communication between Socket
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class BufferedSocketClient {
public static void main(String args[]) throws Exception {
Socket socket1;
int portNumber = 1777;
String str = "initialize";
socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
pw.println(str);
while ((str = br.readLine()) != null) {
System.out.println(str);
pw.println("bye");
if (str.equals("bye"))
break;
}
br.close();
pw.close();
socket1.close();
}
}
///
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class BufferedSocketServer {
public static void main(String args[]) throws Exception {
int cTosPortNumber = 1777;
String str;
ServerSocket servSocket = new ServerSocket(cTosPortNumber);
System.out.println("Waiting for a connection on " + cTosPortNumber);
Socket fromClientSocket = servSocket.accept();
PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));
while ((str = br.readLine()) != null) {
System.out.println("The message: " + str);
if (str.equals("bye")) {
pw.println("bye");
break;
} else {
str = "Server returns " + str;
pw.println(str);
}
}
pw.close();
br.close();
fromClientSocket.close();
}
}
Related examples in the same category