package com.source.myro;
import android.os.Message;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
/*import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.Socket;*/
public class UdpClientThread extends Thread {
String Str;
String dstAddress;
int dstPort;
private boolean running;
MainActivity.UdpClientHandler handler;
DatagramSocket socket;
InetAddress address;
//PrintWriter printWriter; //BufferedReader bufferedReader;
public UdpClientThread(String str, String addr, int port, MainActivity.UdpClientHandler handler) {
super();
Str = str;
dstAddress = addr;
dstPort = port;
this.handler = handler;
}
public void setRunning(boolean running){
this.running = running;
}
private void sendState(String state){
handler.sendMessage(
Message.obtain(handler,
MainActivity.UdpClientHandler.UPDATE_STATE, state));
}
public void txMsg(String msgToSend){
/*if(printWriter != null){ printWriter.println(msgToSend); }*/
try{
socket = new DatagramSocket();
address = InetAddress.getByName(dstAddress);
byte[] sendbuf = new byte[256];
sendbuf = msgToSend.getBytes();
DatagramPacket sendpacket =
new DatagramPacket(sendbuf, sendbuf.length, address, dstPort);
socket.send(sendpacket);
}catch (Exception e) {
e.printStackTrace();
}
}
@Override public void run() {
//sendState("connecting...");
//running = true;
try {
socket = new DatagramSocket();
address = InetAddress.getByName(dstAddress);
// send request byte[] sendbuf = new byte[256];
//String str = "hello"; sendbuf = Str.getBytes();
DatagramPacket sendpacket =
new DatagramPacket(sendbuf, sendbuf.length, address, dstPort);
socket.send(sendpacket);
//handler.sendEmptyMessage(MainActivity.UdpClientHandler.UPDATE_END); if (Str=="hello") {
sendState("connected");
}else if (Str=="end"){
handler.sendEmptyMessage(MainActivity.UdpClientHandler.UPDATE_END);
}
/* String testline="test line"; handler.sendMessage( Message.obtain(handler, MainActivity.UdpClientHandler.UPDATE_MSG, testline)); */ // get response byte[] rcvbuf = new byte[256];
DatagramPacket rcvpacket = new DatagramPacket(rcvbuf, rcvbuf.length);
socket.receive(rcvpacket);
String line = new String(rcvpacket.getData(), 0, rcvpacket.getLength());
//String testline="test line"; handler.sendMessage(
Message.obtain(handler, MainActivity.UdpClientHandler.UPDATE_MSG, line));
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket != null){
socket.close();
//handler.sendEmptyMessage(MainActivity.UdpClientHandler.UPDATE_END); }
}
//handler.sendEmptyMessage(MainActivity.UdpClientHandler.UPDATE_END); //if (running = true){ //sendState("break"); //} }
}
Comments
Post a Comment