服务端
ServerSocket mServer = null;
Socket mServerSocket = null;
int port=8888;
1.初始化服务端
mServer = new ServerSocket(port);
2.建立与客户端的连接,并监听客户端发送的内容
new Thread(new Runnable() {
@Override
public void run() {
try {
mServerSocket = mServer.accept();
SocketAddress ip = mServerSocket.getRemoteSocketAddress();
InputStream inputStream;
try {
inputStream = mServerSocket.getInputStream();
while (!mServerSocket.isClosed()) {
byte[] bs = new byte[5000];
inputStream.read(bs);
String string = new String(bs, "UTF-8");
if (TextUtils.isEmpty(string))
return;
Logger.d(string.trim()+"with服务端接收");
}
} finally {
mServerSocket.close();
}
} catch (IOException e) {
}
}
}).start();
3.发送消息给客户端
new Thread(new Runnable() {
@Override
public void run() {
try {
OutputStream outputStream =
mServerSocket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("服务端发送");
printWriter.flush();
} catch (IOException e) {
}
}
}).start();
客户端
Socket mClientSocket = null;
int port=8888;
1.初始化客户端
new Thread(new Runnable() {
@Override
public void run() {
try {
mClientSocket = new Socket(WifiUtils.getWifiIp(MainActivity.this), port);
initClientInputStream();
} catch (IOException e) {
}
}
}).start();
2.监听服务端发送的消息
private void initClientInputStream() {
if (mClientSocket==null)return;
while(!mClientSocket.isClosed()){
try {
InputStream inputStream = mClientSocket.getInputStream();
byte[] bs=new byte[5000];
inputStream.read(bs);
String s = new String(bs, "UTF-8");
if (TextUtils.isEmpty(s))return;
Logger.d(s.trim()+"with客户端接收");
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.发送消息给服务端
try {
OutputStream outputStream = mClientSocket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("客户端发送");
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
完整代码
页面
public class MainActivity extends AppCompatActivity {
@BindView(R.id.button1)
Button mButton1;
@BindView(R.id.btn2)
Button mBtn2;
ServerSocket mServer = null;
Socket mServerSocket = null;
Socket mClientSocket = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initLogger();
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initServer();
startConnection();
initClient();
}
private void initLogger() {
FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
.tag("meee")
.build();
Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
}
private void initClient() {
new Thread(new Runnable() {
@Override
public void run() {
try {
mClientSocket = new Socket(WifiUtils.getWifiIp(MainActivity.this), 8888);
initClientInputStream();
} catch (IOException e) {
}
}
}).start();
}
private void initClientInputStream() {
if (mClientSocket==null)return;
while(!mClientSocket.isClosed()){
try {
InputStream inputStream = mClientSocket.getInputStream();
byte[] bs=new byte[5000];
inputStream.read(bs);
String s = new String(bs, "UTF-8");
if (TextUtils.isEmpty(s))return;
Logger.d(s.trim()+"with客户端接收");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void initServer() {
try {
mServer = new ServerSocket(8888);
} catch (IOException e) {
}
}
private void startConnection() {
new Thread(new Runnable() {
@Override
public void run() {
try {
mServerSocket = mServer.accept();
SocketAddress ip = mServerSocket.getRemoteSocketAddress();
InputStream inputStream;
try {
inputStream = mServerSocket.getInputStream();
while (!mServerSocket.isClosed()) {
byte[] bs = new byte[5000];
inputStream.read(bs);
String string = new String(bs, "UTF-8");
if (TextUtils.isEmpty(string))
return;
Logger.d(string.trim()+"with服务端接收");
}
} finally {
mServerSocket.close();
}
} catch (IOException e) {
}
}
}).start();
}
@OnClick({R.id.button1, R.id.btn2})
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
new Thread(new Runnable() {
@Override
public void run() {
try {
OutputStream outputStream =
mServerSocket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("服务端发送");
printWriter.flush();
} catch (IOException e) {
}
}
}).start();
break;
case R.id.btn2:
try {
OutputStream outputStream = mClientSocket.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print("客户端发送");
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
布局
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.junx.socket.MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:text="btn1"
app:layout_constraintHorizontal_bias="0.503" app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="8dp"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="btn2" app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button1"
/>
</android.support.constraint.ConstraintLayout>
获取本地ip地址的工具类
public class WifiUtils
{
public static String getWifiIp (Context context)
{
String wifiStr = "";
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()
&& wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED)
{
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null)
{
int ipAddress = wifiInfo.getIpAddress();
if (ipAddress == 0)
{
wifiStr = "";
}
else
{
wifiStr = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff)
+ "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
}
}
}
return wifiStr;
}
}