/// 只是发送端
package com.example.myandroidClient;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button sendButton = null;
private Socket clientSocket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
clientSocket = new Socket(10.255.4.1,8876);}
catch (IOException e)
{
e.printStackTrace();
}
this.sendButton = (Button) findViewById(R.id.send);
this.sendButton.setOnClickListener((OnClickListener) new sendOnClickListener());
private class sendOnClickListener implements OnClickListener {
@Overridepublic void onClick(View v){
try{
PrintStream outPrintStream = new PrintStream(clientSocket.getOutputStream());
outPrintStream.println("I will give you lots of money!");
}
catch (Exception e){e.printStackTrace();
}
}
}
///只是接受端
public class MainActivity extends Activity {
private ServerSocket server = null;
private Socket socket = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listenClient();
}
public void listenClient(){
try {
server = new ServerSocket(8876);
System.out.println("Listening Succeed!");
socket = server.accept();
System.out.println("Listen a new connect!");
}
catch (IOException e) {
e.printStackTrace();
}BufferedReader bufferedReader = null;
try {
while(!socket.isClosed()){
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(!bufferedReader.ready()){
String string = bufferedReader.readLine();
System.out.println(string);}
}
bufferedReader.close();
outsendStream.close();
socket.close();server.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
我把接收端和发送端分开写了,感觉这样比较的清晰和明了,如何要合并的话,只需要把其中的一个类已过去就行。
注意这里所有打开的流和服务都没有关闭,主要是为了能一直发送和接收,如果想多个客户端同时连接的话,可以再建个线程即可。