简单实现Socket编程代码
-
本程序只实现单向发送就是服务器向客户端发送信息(如果你想两边都可以互相发送就百度查找,当时我自己也是慢慢摸索出来的)
-
建议用idea编译器
-
服务器代码
package Socket;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Service {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8080);//在本机绑定到指定的端口,并且侦听客户端请求。
Socket accept = serverSocket.accept();//接收请求,建立socket对象
PrintWriter printWriter = new PrintWriter(accept.getOutputStream());
while (true){
Scanner input = new Scanner(System.in);
String msg = input.nextLine();
printWriter.println(msg);
printWriter.flush();
if (msg.equals("拜拜")) break;
}
printWriter.close();
accept.close();
serverSocket.close();
}
}
- 客户端代码
package Socket;
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("localhost", 8080);//首先你得得到本机端口和端口号
InputStream inputStream = socket.getInputStream();//创建字节输入流接收信息
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));//创建字符流接收服务器发来文本
while (true){//顺环是为了持续接收信息
String msg = bufferedReader.readLine();
System.out.println(msg);
if (msg.equals("拜拜")) break;//当服务器发给用户拜拜后就退出程序
}
bufferedReader.close();//以下三个是关闭相关流
inputStream.close();
socket.close();
}
}