接收端(服務(wù)端)中的socket要實(shí)時(shí)處于監(jiān)聽(tīng)狀態(tài),即要設(shè)置一個(gè)死循環(huán)。
創(chuàng)新互聯(lián)公司專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于成都網(wǎng)站制作、成都做網(wǎng)站、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、富民網(wǎng)絡(luò)推廣、微信小程序、富民網(wǎng)絡(luò)營(yíng)銷、富民企業(yè)策劃、富民品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營(yíng)等,從售前售中售后,我們都將竭誠(chéng)為您服務(wù),您的肯定,是我們最大的嘉獎(jiǎng);創(chuàng)新互聯(lián)公司為所有大學(xué)生創(chuàng)業(yè)者提供富民建站搭建服務(wù),24小時(shí)服務(wù)熱線:18982081108,官方網(wǎng)址:www.cdcxhl.com
例如:
while(1){
//.....
}
當(dāng)接收到一個(gè)客戶端的消息,再為其開(kāi)辟新的進(jìn)程進(jìn)行數(shù)據(jù)處理。
我也只是說(shuō)個(gè)大概,具體建議網(wǎng)絡(luò)上百度一下socket通信方法,看看人家服務(wù)器端是怎么寫的。
你這根本什么都沒(méi)寫啊,原來(lái)寫了個(gè)模擬QQ的,不過(guò)沒(méi)去畫界面,供你參考下,希望能幫到你,主要的是你把原理弄清楚就應(yīng)該沒(méi)問(wèn)題了
服務(wù)器:
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.regex.*;
public class Server
{
/**
* @param args
*/
private int count = 0;
private int num = 0;
HashMapInteger,Socket clients = new HashMapInteger,Socket();
public Server()
{
try
{
ServerSocket server = new ServerSocket(33333);
while(true)
{
Socket fromClient = server.accept();
count++;
num++;
clients.put(count, fromClient);
new Thread()
{
public void run()
{
receive();
}
}.start();
new Thread()
{
public void run()
{
send();
}
}.start();
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive()
{
try
{
BufferedReader read = new BufferedReader(new InputStreamReader(clients.get(count).getInputStream()));
int tmp = count;
int temp = 0;
while(true)
{
String value = "";
try
{
value = read.readLine();
String regex = "^ *~ *(\\d+) *:(.*)";
Pattern pat = Pattern.compile(regex);
Matcher match = pat.matcher(value);
if(match.find())
{
temp = Integer.valueOf(match.group(1));
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(temp).getOutputStream()));
write.write("用戶"+tmp+":"+match.group(2)+"\n");
write.flush();
}
else
{
for(int i = 1;i=num;i++)
{
if(i == tmp)
{
continue;
}
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
write.write("用戶"+tmp+":"+value + "\n");
write.flush();
}
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch(IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void send()
{
Scanner scan = new Scanner(System.in);
String tmp = "";
while(!tmp.equals("exit"))
{
tmp = scan.nextLine();
try
{
for(int i = 1;i=num;i++)
{
BufferedWriter write = new BufferedWriter(new OutputStreamWriter(clients.get(i).getOutputStream()));
write.write("系統(tǒng):"+tmp + "\n");
write.flush();
}
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Server();
}
}
客戶端:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
/**
* @param args
*/
BufferedReader read;
BufferedWriter write;
public Client()
{
try
{
Socket client = new Socket("192.168.1.7",33333);
read = new BufferedReader(new InputStreamReader(client.getInputStream()));
write = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
new Thread()
{
public void run()
{
recieve();
}
}.start();
new Thread()
{
public void run()
{
send();
}
}.start();
//send();
}
catch(UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send()
{
Scanner scan = new Scanner(System.in);
String tmp = "";
while(!tmp.equals("exit"))
{
tmp = scan.nextLine();
try
{
tmp= tmp+"\n";
write.write(tmp);
write.flush();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void recieve()
{
while(true)
{
try
{
String value = "";
value = read.readLine();
System.out.println(value);
write.flush();
}
catch(IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
new Client();
}
}
Server代碼
package?com.javacodegeeks.android.androidsocketserver;
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStreamReader;
import?java.net.ServerSocket;
import?java.net.Socket;
import?android.app.Activity;
import?android.os.Bundle;
import?android.os.Handler;
import?android.util.Log;
import?android.widget.TextView;
public?class?Server?extends?Activity
{
private?ServerSocket?serverSocket;
private?Handler?updateConversationHandler;
private?Thread?serverThread?=?null;
private?TextView?text;
public?static?final?int?SERVERPORT?=?6000;
@Override
public?void?onCreate(Bundle?savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text?=?(TextView)?findViewById(R.id.text2);
updateConversationHandler?=?new?Handler();
this.serverThread?=?new?Thread(new?ServerThread());
this.serverThread.start();
}
@Override
protected?void?onStop()
{
super.onStop();
try
{
serverSocket.close();
}
catch?(IOException?e)
{
e.printStackTrace();
}
}
private?class?ServerThread?implements?Runnable
{
public?void?run()
{
Socket?socket?=?null;
try
{
serverSocket?=?new?ServerSocket(SERVERPORT);
}
catch?(IOException?e)
{
e.printStackTrace();
}
while?(!Thread.currentThread().isInterrupted())
{
try
{
socket?=?serverSocket.accept();?//?TODO
CommunicationThread?commThread?=?new?CommunicationThread(socket);
new?Thread(commThread).start();
}
catch?(IOException?e)
{
Log.i("liu",?"socket.accept()失敗");
e.printStackTrace();
}
}
}
}
private?class?CommunicationThread?implements?Runnable
{
private?Socket?clientSocket;
private?BufferedReader?input;
public?CommunicationThread(Socket?clientSocket)
{
this.clientSocket?=?clientSocket;
Log.i("liu",?"獲取到了client的Socket");
try
{
this.input?=?new?BufferedReader(new?InputStreamReader(this.clientSocket.getInputStream()));?//?TODO
}
catch?(IOException?e)
{
Log.i("liu",?"input獲取失敗");
e.printStackTrace();
}
}
public?void?run()
{
while?(!Thread.currentThread().isInterrupted())
{
try
{
String?read?=?input.readLine();?//?TODO
Log.i("liu",?read);
updateConversationHandler.post(new?updateUIThread(read));
}
catch?(IOException?e)
{
Log.i("liu",?"input讀取失敗");
e.printStackTrace();
}
}
}
}
private?class?updateUIThread?implements?Runnable
{
private?String?msg;
public?updateUIThread(String?str)
{
this.msg?=?str;
}
@Override
public?void?run()
{
text.setText(text.getText().toString()?+?"Client?Says:?"?+?msg?+?"\n");
}
}
}
2. Client代碼:
package?com.javacodegeeks.android.androidsocketclient;
import?java.io.BufferedWriter;
import?java.io.IOException;
import?java.io.OutputStreamWriter;
import?java.io.PrintWriter;
import?java.net.InetAddress;
import?java.net.Socket;
import?java.net.UnknownHostException;
import?android.app.Activity;
import?android.os.Bundle;
import?android.util.Log;
import?android.view.View;
import?android.widget.EditText;
public?class?Client?extends?Activity
{
private?Socket?socket;
private?static?final?int?SERVERPORT?=?4000;
private?static?final?String?SERVER_IP?=?"10.0.2.2";
@Override
public?void?onCreate(Bundle?savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new?Thread(new?ClientThread()).start();
}
public?void?onClick(View?view)
{
try
{
EditText?et?=?(EditText)?findViewById(R.id.EditText01);
String?str?=?et.getText().toString();
Log.i("liu",?"點(diǎn)擊按鈕");
PrintWriter?out?=?new?PrintWriter(new?BufferedWriter(new?OutputStreamWriter(socket.getOutputStream())),?true);?//?TODO
out.println(str);
}
catch?(Exception?e)
{
Log.i("liu",?"write失敗");
e.printStackTrace();
}
}
class?ClientThread?implements?Runnable
{
@Override
public?void?run()
{
try
{
InetAddress?serverAddr?=?InetAddress.getByName(SERVER_IP);
socket?=?new?Socket(serverAddr,?SERVERPORT);
}
catch?(UnknownHostException?e1)
{
e1.printStackTrace();
}
catch?(IOException?e1)
{
e1.printStackTrace();
}
}
}
}