sending and receiving with sockets in java?
Posted
by
Darksole
on Stack Overflow
See other posts from Stack Overflow
or by Darksole
Published on 2013-11-01T21:49:58Z
Indexed on
2013/11/01
21:53 UTC
Read the original article
Hit count: 242
I am working on sending and receiving from clients and servers in java, and am stumped at the moment. the client socket is to contact a server at “localhost” port 4321. The client will receive a
string from the server and alternate spelling the contents of this string with the server. For example,
given the string “Bye Bye”, the client (which always begins sending the first letter) sends “B”, receives
“y”, sends “e”, receives “ ”, sends “B”, receives “y”, sends “e”, and receives “done!”, which is the string
that either client or server will send after the last letter from the original string is received. After “done!”
is transmitted, both client and server close their communications. How would i go about getting the first string and then going back and forth sending and reciving letters that make the string, and when finished either send or get done!?
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Program2 {
public static void goClient() throws UnknownHostException, IOException{
String server = "localhost";
int port = 4321;
Socket socket = new Socket(server, port);
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
Scanner in = new Scanner(inStream);
PrintWriter out = new PrintWriter(outStream, true);
String rec = "";
if(in.hasNext()){
rec = in.nextLine();
}
char[] array = new char[rec.length()];
for(int i = 0; i < rec.length(); i++){
array[i] = rec.charAt(i);
}
while(in.hasNext()){
for(int x = 0; x < array.length + 1; x+=2){
String str = in.nextLine();
str = Character.toString(array[x]);
out.println(str);
}
in.close();
socket.close();
}
}
}
© Stack Overflow or respective owner