说明:在java通信中有UDP和TCP2种类型,这里只说明TCP通信,通信分为服务端和客户端2个类的代码
注意:
1、在启动项目的时候首先要启动服务器端(TCPService)的代码,然后启动客户端的代码(TCPClient)就可以在服务端的控制台就可以看到客户端发送的数据
2、如果需要不停止服务器,可以使用死循环
最后:这里只是简单的案例展示,如果有特殊的需求解决不了,可以留言。
服务器端代码展示:
package com.rabbit.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* TODO TCP通信服务器
* create 2017年2月19日 下午3:49:15
* @author rabbit先生
*/
public class TCPService {
public static void main(String[] args) throws IOException {
System.out.println("TCPserver启动......");
//1.创建ServiceSocket监听8888端口
ServerSocket serverSocket = new ServerSocket(8888);
//2.监听端口
Socket socket = serverSocket.accept();
//3.获取监听到的Socket中的输出流
InputStream is = socket.getInputStream();
//4.获取发送数据端的地址对象
InetAddress address = socket.getInetAddress();
//5.获取连接主机名称和IP
String hostName = address.getHostName();
String hostAddress = address.getHostAddress();
//6.读取数据
byte[] bytes = new byte[1024];
int length = is.read(bytes);
String message = new String(bytes, 0, length);
System.out.println("客户:" + hostName + ",IP:" + hostAddress + ",发送信息:" + message);
//关闭客户端
socket.close();
//关闭服务器
serverSocket.close();
}
}
客户端代码展示:
package com.rabbit.tcp;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
/**
* TODO TCP客户端
* create 2017年2月19日 下午4:04:55
* @author rabbit先生
*/
public class TCPClient {
public static void main(String[] args) throws IOException {
System.out.println("TCP客户端启动......");
//创建Socket对象
Socket socket = new Socket("192.168.1.101", 8888);
//获取输出流
OutputStream os = socket.getOutputStream();
//写出数据
os.write("这是TCP客户端发送的数据...".getBytes());
//关闭流
os.close();
}
}