上一節(jié)的概念課枯燥無味是吧,不過總有點收獲是吧,本節(jié)開始我們來研究基于TCP協(xié)議的Socket 通信,先來了解下Socket的概念,以及Socket通信的模型,實現(xiàn)Socket的步驟,以及作為Socket服務 端與客戶端的兩位各做要做什么事情!好的,我們由淺入深來扣這個Socket吧!
Socket通信實現(xiàn)步驟解析:
Step 1:創(chuàng)建ServerSocket和Socket
Step 2:打開連接到的Socket的輸入/輸出流
Step 3:按照協(xié)議對Socket進行讀/寫操作
Step 4:關閉輸入輸出流,以及Socket
好的,我們接下來寫一個簡單的例子,開啟服務端后,客戶端點擊按鈕然后鏈接服務端, 并向服務端發(fā)送一串字符串,表示通過Socket鏈接上服務器~
服務端要做的事有這些:
Step 1:創(chuàng)建ServerSocket對象,綁定監(jiān)聽的端口
Step 2:調用accept()方法監(jiān)聽客戶端的請求
Step 3:連接建立后,通過輸入流讀取客戶端發(fā)送的請求信息
Step 4:通過輸出流向客戶端發(fā)送響應信息
Step 5:關閉相關資源
代碼實現(xiàn):
直接在Eclipse下創(chuàng)建一個Java項目,然后把Java代碼貼進去即可!
public class SocketServer {
public static void main(String[] args) throws IOException {
//1.創(chuàng)建一個服務器端Socket,即ServerSocket,指定綁定的端口,并監(jiān)聽此端口
ServerSocket serverSocket = new ServerSocket(12345);
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
Socket socket = null;
//2.調用accept()等待客戶端連接
System.out.println("~~~服務端已就緒,等待客戶端接入~,服務端ip地址: " + ip);
socket = serverSocket.accept();
//3.連接后獲取輸入流,讀取客戶端信息
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
OutputStream os=null;
PrintWriter pw=null;
is = socket.getInputStream(); //獲取輸入流
isr = new InputStreamReader(is,"UTF-8");
br = new BufferedReader(isr);
String info = null;
while((info=br.readLine())!=null){//循環(huán)讀取客戶端的信息
System.out.println("客戶端發(fā)送過來的信息" + info);
}
socket.shutdownInput();//關閉輸入流
socket.close();
}
}
然后我們把代碼run起來,控制臺會打?。?/p>
好的,接下來到Android客戶端了!
客戶端要做的事有這些:
Step 1:創(chuàng)建Socket對象,指明需要鏈接的服務器的地址和端號
Step 2:鏈接建立后,通過輸出流向服務器發(fā)送請求信息
Step 3:通過輸出流獲取服務器響應的信息
Step 4:關閉相關資源
代碼實現(xiàn):
MainActivity.java:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_accept = (Button) findViewById(R.id.btn_accept);
btn_accept.setOnClickListener(this);
}
@Override
public void onClick(View v) {
new Thread() {
@Override
public void run() {
try {
acceptServer();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
private void acceptServer() throws IOException {
//1.創(chuàng)建客戶端Socket,指定服務器地址和端口
Socket socket = new Socket("172.16.2.54", 12345);
//2.獲取輸出流,向服務器端發(fā)送信息
OutputStream os = socket.getOutputStream();//字節(jié)輸出流
PrintWriter pw = new PrintWriter(os);//將輸出流包裝為打印流
//獲取客戶端的IP地址
InetAddress address = InetAddress.getLocalHost();
String ip = address.getHostAddress();
pw.write("客戶端:~" + ip + "~ 接入服務器??!");
pw.flush();
socket.shutdownOutput();//關閉輸出流
socket.close();
}
}
因為Android不允許在主線程(UI線程)中做網絡操作,所以這里需要我們自己 另開一個線程來連接Socket!
運行結果:
點擊按鈕后,服務端控制臺打?。?/p>
只是點擊個按鈕,然后服務器返回一串信息,肯定是很無趣的是吧,接下來我們來 搭建一個超簡單的聊天室,我們需要用到線程池,存儲Socket鏈接的集合,我們還需要 字節(jié)寫一個線程,具體的我們在代碼中來體會!
實現(xiàn)的效果圖:
先把我們的服務端跑起來:
接著把我們的程序分別跑到兩臺模擬器上:
接下來我們來寫代碼:
首先是服務端,就是將讀寫socket的操作放到自定義線程當中,創(chuàng)建ServerSocket后,循環(huán) 調用accept方法,當有新客戶端接入,將socket加入集合當中,同時在線程池新建一個線程!
另外,在讀取信息的方法中,對輸入字符串進行判斷,如果為bye字符串,將socket從集合中 移除,然后close掉!
Server.java:
public class Server {
//定義相關的參數(shù),端口,存儲Socket連接的集合,ServerSocket對象
//以及線程池
private static final int PORT = 12345;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService myExecutorService = null;
public static void main(String[] args) {
new Server();
}
public Server()
{
try
{
server = new ServerSocket(PORT);
//創(chuàng)建線程池
myExecutorService = Executors.newCachedThreadPool();
System.out.println("服務端運行中...\n");
Socket client = null;
while(true)
{
client = server.accept();
mList.add(client);
myExecutorService.execute(new Service(client));
}
}catch(Exception e){e.printStackTrace();}
}
class Service implements Runnable
{
private Socket socket;
private BufferedReader in = null;
private String msg = "";
public Service(Socket socket) {
this.socket = socket;
try
{
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msg = "用戶:" +this.socket.getInetAddress() + "~加入了聊天室"
+"當前在線人數(shù):" +mList.size();
this.sendmsg();
}catch(IOException e){e.printStackTrace();}
}
@Override
public void run() {
try{
while(true)
{
if((msg = in.readLine()) != null)
{
if(msg.equals("bye"))
{
System.out.println("~~~~~~~~~~~~~");
mList.remove(socket);
in.close();
msg = "用戶:" + socket.getInetAddress()
+ "退出:" +"當前在線人數(shù):"+mList.size();
socket.close();
this.sendmsg();
break;
}else{
msg = socket.getInetAddress() + " 說: " + msg;
this.sendmsg();
}
}
}
}catch(Exception e){e.printStackTrace();}
}
//為連接上服務端的每個客戶端發(fā)送信息
public void sendmsg()
{
System.out.println(msg);
int num = mList.size();
for(int index = 0;index < num;index++)
{
Socket mSocket = mList.get(index);
PrintWriter pout = null;
try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(mSocket.getOutputStream(),"UTF-8")),true);
pout.println(msg);
}catch (IOException e) {e.printStackTrace();}
}
}
}
}
接著到客戶端,客戶端的難點在于要另外開辟線程的問題,因為Android不允許直接在 主線程中做網絡操作,而且不允許在主線程外的線程操作UI,這里的做法是自己新建 一個線程,以及通過Hanlder來更新UI,實際開發(fā)不建議直接這樣做!??!
布局文件:activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小豬簡易聊天室" />
<TextView
android:id="@+id/txtshow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/editsend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/btnsend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="發(fā)送"
/>
</LinearLayout>
MainActivity.java:
public class MainActivity extends AppCompatActivity implements Runnable {
//定義相關變量,完成初始化
private TextView txtshow;
private EditText editsend;
private Button btnsend;
private static final String HOST = "172.16.2.54";
private static final int PORT = 12345;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
private StringBuilder sb = null;
//定義一個handler對象,用來刷新界面
public Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x123) {
sb.append(content);
txtshow.setText(sb.toString());
}
}
;
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = new StringBuilder();
txtshow = (TextView) findViewById(R.id.txtshow);
editsend = (EditText) findViewById(R.id.editsend);
btnsend = (Button) findViewById(R.id.btnsend);
//當程序一開始運行的時候就實例化Socket對象,與服務端進行連接,獲取輸入輸出流
//因為4.0以后不能再主線程中進行網絡操作,所以需要另外開辟一個線程
new Thread() {
public void run() {
try {
socket = new Socket(HOST, PORT);
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
//為發(fā)送按鈕設置點擊事件
btnsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String msg = editsend.getText().toString();
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
}
}
}
});
new Thread(MainActivity.this).start();
}
//重寫run方法,在該方法中輸入流的讀取
@Override
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {
if ((content = in.readLine()) != null) {
content += "\n";
handler.sendEmptyMessage(0x123);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
好的,本節(jié)給大家講解了基于TCP的Socket通信,文中介紹了Socket通信的模型,實現(xiàn)了 一個簡單的Socket通信例子,以及寫了一個增強版的實例:小豬聊天室,相信會對剛涉及 Socket編程的你帶來便利~,謝謝~
更多建議: