Socket不断报错!!(记得\n要加上,以及Socket上流通的是字节!还有Socket需要借助数据流来完成数据传递工作,注意输入流的导包不要导入错误,是io流包)

Socket不断报错!!(记得\n要加上,以及Socket上流通的是字节!还有Socket需要借助数据流来完成数据传递工作,注意输入流的导包不要导入错误,是io流包)

1,在Socket 客户端上写入的是字节。

 

错误代码:

 

 2,Socket 客户端写入请求指令要以 \n 结尾(这里报错添加\n后正确的根本原因:“引自评论者: 小新动感光波”:)

【ps:\n结束是因为你用了readLine,socket并没有强制要求你用\n作为结尾。

 错误代码:

 

 

3,io 流导错包了,快捷键ctr+shift +o 导的包可能是第一个位置的“import org.omg.CORBA.portable.InputStream;”

 

✌全部代码:

❀class TCPServerSocket

package TCPDemo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * TCP服务端
 * @author Huangyujun
 *
 */
public class TCPServerSocket {
    private final static int port = 9527;
    public static void main(String[] args) throws IOException {
        //建立服务端
        ServerSocket serverSocket = new ServerSocket(port);
        //接收客户端
        System.out.println("服务端已经开启~");
        Socket clientSocket = serverSocket.accept();
        //输入流、输出流
        InputStream inStream =  clientSocket.getInputStream();
        OutputStream outStream = clientSocket.getOutputStream();
        //打印接受的内容
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(inStream));
        String line = bufferRead.readLine();
        System.out.println("服务端已经接收消息:"  + line);
    }
}

❀class TCPSocket

package TCPDemo;


import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;



/**
 * 客户端Socket
 * @author Huangyujun
 *
 */
public class TCPSocket {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        Socket socket = new Socket("localhost", 9527);    //连接服务端
        System.out.println("客户端发送消息:");
        String content  = scanner.next();
//        content += "\n";
        //输出流、输入流
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream =  socket.getInputStream();
        //发送消息
        BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(outStream));
//        bufferWriter.write(content);
        outStream.write(content.getBytes());
        
    }
}

 

posted @ 2021-05-24 11:15  一乐乐  阅读(276)  评论(2编辑  收藏  举报