//运行在手机真机上的 package com.example.administrator.client; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.EditText; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; public class MainActivity extends Activity { EditText show; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); show = (EditText) findViewById(R.id.show); new Thread() { @Override public void run() { try { // 创建客户端的socket服务,指定目的主机和端口 Socket s = new Socket("192.168.1.103" , 30000); //2为了发送数据,应该获取socket流中的输出流 OutputStream out = s.getOutputStream(); out.write("tcp 的例子".getBytes()); s.close(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } }
//运行在电脑上的 import java.util.concurrent.locks.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.net.*; public class recv { public static void main(String[]args)throws Exception { //1、建立服务端的socket服务,并监听一个端口 ServerSocket ss = new ServerSocket(30000); //2、通过accept方法获取连接过来的客户端对象 Socket s = ss.accept(); String ip = s.getInetAddress().getHostAddress();//获取客户端IP int port = s.getPort(); //获取客户端端口 System.out.println(ip); System.out.println(port); //3、获取客户端发送过来的数据,那么要使用客户端对象的读取流来读取数据 InputStream in = s.getInputStream(); byte [] buf = new byte[1024]; int len = in.read(buf); System.out.println(new String(buf, 0, len)); s.close(); ss.close(); } }
解决方案
20
try {
Socket s = new Socket(“192.168.1.103” , 30000);
OutputStream out = s.getOutputStream();
String str = “tcp 的例子”;
byte str_bytes = str.getBytes(“utf-8”);
out.write(str_bytes);
}catch (Exception e) {
// do nothing
}
这样?
Socket s = new Socket(“192.168.1.103” , 30000);
OutputStream out = s.getOutputStream();
String str = “tcp 的例子”;
byte str_bytes = str.getBytes(“utf-8”);
out.write(str_bytes);
}catch (Exception e) {
// do nothing
}
这样?