socket服务端
package com.chen.socketServer;
import java.net.*;
import java.io.*;
/**
socke服务端代码
*/
public class ScoketServer
{
public static void main(String[] args)
throws IOException
{
//打印本机的IP地址
InetAddress address=InetAddress.getLocalHost();
System.out.println("本机的IP地址是"+address.getHostAddress());
// 创建一个ServerSocket,用于监听客户端Socket的连接请求
ServerSocket ss = new ServerSocket(30000);
// 采用循环不断接受来自客户端的请求
while (true)
{
// 每当接受到客户端Socket的请求,服务器端也对应产生一个Socket
Socket s = ss.accept();
// 将Socket对应的输出流包装成PrintStream
PrintStream ps = new PrintStream(s.getOutputStream());
// 进行普通IO操作
ps.println("您好,您收到了服务器的新年祝福!");
// 关闭输出流,关闭Socket
ps.close();
s.close();
}
}
}
socket客户端
package com.chen.socketClient;
/**
socket客户端代码
*/
import java.net.*;
import java.io.*;
public class SocketClient
{
public static void main(String[] args)
throws IOException
{
//Socket socket = new Socket("127.0.0.1" , 30000);
Socket socket = new Socket("192.168.119.35" , 30000);//这里的IP地址填写手机端服务器的IP地址
// 将Socket对应的输入流包装成BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 进行普通IO操作
String line = br.readLine();
System.out.println("来自服务器的数据:" + line);
// 关闭输入流、socket
br.close();
socket.close();
}
}