客户端与服务器端的简单通信:
服务器端:
package com.main.java; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { try { //新建serversocket对象 ServerSocket serverSocket=new ServerSocket(12306); System.out.println("服务器端开始监听"); //监听 Socket socket=serverSocket.accept(); //输入流 InputStream is=socket.getInputStream(); //解析数据 InputStreamReader ir=new InputStreamReader(is); BufferedReader br=new BufferedReader(ir); String s=null; StringBuffer sb=new StringBuffer(); while((s=br.readLine())!=null) { sb.append(s); } System.out.println("客户端发来数据:"+sb.toString()); socket.shutdownInput(); OutputStream os=socket.getOutputStream(); os.write(sb.toString().getBytes()); os.flush(); socket.shutdownOutput(); os.close(); br.close(); ir.close(); is.close(); socket.close(); serverSocket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
客户端:
public class MainActivity extends AppCompatActivity { private Button button; private TextView textView; private EditText editText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=findViewById(R.id.butt); textView=findViewById(R.id.textv); editText=findViewById(R.id.edit); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { //监听指定服务器ip Socket socket=new Socket("123.56.137.134",12306); //输出流 OutputStream os=socket.getOutputStream(); //写入数据 os.write(editText.getText().toString().getBytes()); os.flush(); socket.shutdownOutput(); //输入流 InputStream is=socket.getInputStream(); //解析返回的数据 InputStreamReader reader=new InputStreamReader(is); BufferedReader br=new BufferedReader(reader); String s=""; final StringBuffer stringBuffer=new StringBuffer(); while ((s=br.readLine())!=null){ stringBuffer.append(s); } runOnUiThread(new Runnable() { @Override public void run() { textView.setText(stringBuffer.toString()); } }); br.close(); reader.close(); is.close(); os.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }); }