Java服务器与客户端的连接
客户端程序
server.java
package com.sram.sever;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Sever {
public static void main(String[] args) throws Exception{
ServerSocket serverSocket =new ServerSocket(5555);
System.out.println("服务端已经启动,等待客户端输入********");
while(true)
{
Socket client=serverSocket.accept();
//使用简单的流来输出
//此打印流就是服务器先客户端输出的信息流
PrintStream printstream= new PrintStream(client.getOutputStream());
//printstream.println("liuxingruichoubi");
BufferedReader readerClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
String clientStr=readerClient.readLine();
System.out.println("接收到了---->"+clientStr);
printstream.println("接收到了---->"+clientStr);
}
}
}
服务器程序
client.java
package com.sram.sever;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import javax.print.PrintService;
public class client {
public static void main(String[] args) throws Exception{
Socket client =new Socket("192.168.0.12",5555);
//创建对象读取服务端发送内容,转换流
//字符输入流
BufferedReader readerServer = new BufferedReader(new InputStreamReader(client.getInputStream()));
//向服务端输出内容
PrintStream printstream= new PrintStream(client.getOutputStream());
//读取控制台输入流
BufferedReader readerConsole = new BufferedReader(new InputStreamReader(System.in));
String consoleStr=readerConsole.readLine();
//将控制台的内容发送给服务端
printstream.println(consoleStr);
String serverStr=readerServer.readLine();
System.out.println("服务器返回内容:"+serverStr);
}
}
通信协议