Wed Feb 06, 2013 10:13 pm
import java.io.*;
import java.net.*;
import java.util.*;
public class TextClient {
public static void main(String[] args) throws IOException {
String ipAdress="112.43.54.1";
String hostName="HostNameHere";
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(hostName);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData(), 0);
System.out.println("Text of the Moment: " + received);
socket.close();
}
}
public class TextServer {
public static void main(String[] args) throws java.io.IOException {
new TextServerThread().start();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
public class TextServerThread extends Thread {
private DatagramserverSocket serverSocket = null;
private DataInputStream in = null;
private boolean moreTexts = true;
public TextServerThread() throws IOException {
super("TextServerThread");
serverSocket = new DatagramserverSocket(4445);
try {
// Read from file
in = new DataInputStream(new FileInputStream("data.txt"));
} catch (FileNotFoundException e) {
System.err.println("Could not open Text file. Serving time instead.");
}
}
public void run() {
while (moreTexts) {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
serverSocket.receive(packet);
// figure out response
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getMoreData();
dString.getBytes(0, dString.length(), buf, 0);
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
serverSocket.send(packet);
} catch (IOException e) {
e.printStackTrace();
moreTexts = false;
}
}
serverSocket.close();
}
private String getMoreData() {
String returnValue = null;
try {
if ((returnValue = in.readLine()) == null) {
in.close();
moreTexts = false;
returnValue = "No more Data. ";
}
} catch (IOException e) {
returnValue = "IOException occurred in server.";
}
return returnValue;
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.