Android学习笔记_Socket编程(tcp/udp)
socket编程
public class SocketActivity extends Activity{
private Button startButton=null;
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
startButton = (Button)findViewById(R.id.startButton);
startButton.setOnClickListener(new StartSocketListener());
}
class StartSocketListener implements OnClickListener{
public void onClick(){
new ServerThread().start();
}
}
class ServerThread extends Thread{
public void run(){
ServerSocket serverSocket=null;
try{
serverSocket = new ServerSocket(3456);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte buffer [] = new byte[1024];
int temp = 0;
while((temp = inputStream.read(buffer)) !=-1){
System.out.println(new String(buffer,0,temp));
}
}catch(IOException e){
e.printStackTrace();
}finally{
try{
serverSocket.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
public class TCPClient{
public static void main(String[] args){
try{
Socket socket = new Socket("192.168.0.100",3456);
InputStream inputStream = new FileInputStream("f://file/words.txt");
OutputStream outputStream = socket.getOutputStream();
byte buffer[] = new byte[4*1024];
int temp=0;
while((temp=inputStream.read(buffer))!=-1){
outputStream.write(buffer,0,temp);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
UDP协议下的SocketActivity中的run()方法
public void run(){
try{
DatagramSocket socket=new DatagramSocket(4567);
byte data[]=new byte[1024];
DatagramPacket packet = new DatagramPacket(data,data.length);
socket.receive(packet);
String result= new String(packet.getData(),packet.getOffset(),packet.getLength());
System.out.println("result----->"+result);
}
}
public class UDPClient{
public static void main(String[] args){
try{
DatagramSocket socket = new DatagramSocket(3456);
InetAddress serverAddress = InetAddress.getByName("192.168.1.100");
String str= "hello";
byte data[]=str.getBytes();
DatagramPacket packet = new DatagramPacket(data,data.length,serverAddress,3456);
socket.send(packet);
}catch(Exception e){
e.printStackTrace();
}
}
}