服务器端:
try {
ServerSocket ss = new ServerSocket(8888);
System.out.println("Listening...");
while (true) {
Socket socket = ss.accept();
System.out.println("Cilent Connected...");
DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
String str = "Socket通信";
dout.writeUTF(str);
dout.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
客户端:
try {
Socket socket = new Socket("192.168.0.103", 8888);DataInputStream din = new DataInputStream(socket.getInputStream());
String msg = din.readUTF();
Toast.makeText(SocketActivity.this, msg, Toast.LENGTH_LONG).show();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
网络连接要建立新的线程,不要在主线程操作。可以利用AsyncTask<Void, String, Void>异步处理。
写入:socket=new Socket(mIp.getText().toString(),8888);
bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writes=new DataOutputStream(socket.getOutputStream());
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
bw.write(“。。。。。”);写入想要发送内容。 read为读取内容!
protected Void doInBackground(Void... arg0) {
try {
socket=new Socket(mIp.getText().toString(),8888);
bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writes=new DataOutputStream(socket.getOutputStream());
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
publishProgress("@success");
Toast.makeText(MainActivity.this, "链接try!?|??", Toast.LENGTH_LONG).show();
} catch (UnknownHostException e1) {
Toast.makeText(MainActivity.this, "链接失敗!!!!!", Toast.LENGTH_LONG).show();
e1.printStackTrace();
} catch (IOException e1) {
Toast.makeText(MainActivity.this, "链接失敗!!", Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
try {
String line;
line = br.readLine();
while(line!=null){
publishProgress(line);
Toast.makeText(MainActivity.this, "链接失敗!!", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
Toast.makeText(MainActivity.this, "链接失敗!!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return null;
}