ServerTest.java
import java.io.*;import java.net.*;
public class ServerTest implements Serializable {
String[] messageList = {
"Mai bine sa ai bani decat sa nu ai.",
"Din putul gandirii.",
"Cosorul lui Moceanu a fost inventat de Moceanu",
"Da' ce am facut sefu'?",
"Elefantul si bursucul."
};
public static void main(String[] args) {
ServerTest server = new ServerTest();
server.setupServer();
}
public void setupServer() {
try {
ServerSocket serverSock = new ServerSocket(5000);
//each time a client open a socket respond with one message from messageList
while (true) {
Socket sock = serverSock.accept();
PrintWriter writer = new PrintWriter(sock.getOutputStream());
String advice = getAdvice();
writer.println(advice);
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private String getAdvice() {
int random = (int)(Math.random() * messageList.length);
return messageList[random];
}
}
ClientTest.java
import java.io.*;
import java.net.*;
public class ClientTest implements Serializable {
public static void main(String[] args) {
ClientTest client = new ClientTest();
client.ReadStreamFromNET();
}
public void ReadStreamFromNET() {
try {
Socket chatSocket = new Socket("127.0.0.1", 5000);
InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());
BufferedReader reader = new BufferedReader (stream);
String message = reader.readLine();
System.out.println("\t" + message);
} catch(IOException ex) {
ex.printStackTrace();
}
}
public void WriteStreamToNET() {
try {
Socket chatSocket = new Socket("127.0.0.1", 5000);
//Connection output stream
PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());
writer.println("message to send");
writer.print("another message");
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
import java.net.*;
public class ClientTest implements Serializable {
public static void main(String[] args) {
ClientTest client = new ClientTest();
client.ReadStreamFromNET();
}
public void ReadStreamFromNET() {
try {
Socket chatSocket = new Socket("127.0.0.1", 5000);
InputStreamReader stream = new InputStreamReader(chatSocket.getInputStream());
BufferedReader reader = new BufferedReader (stream);
String message = reader.readLine();
System.out.println("\t" + message);
} catch(IOException ex) {
ex.printStackTrace();
}
}
public void WriteStreamToNET() {
try {
Socket chatSocket = new Socket("127.0.0.1", 5000);
//Connection output stream
PrintWriter writer = new PrintWriter(chatSocket.getOutputStream());
writer.println("message to send");
writer.print("another message");
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
Niciun comentariu:
Trimiteți un comentariu