简体   繁体   English

套接字编程客户端服务器Java

[英]socket programming client server java

I'm trying to implement a TCP send and receive program between a client and a server. 我正在尝试在客户端和服务器之间实现TCP发送和接收程序。 They exchange info. 他们交流信息。 continuously by using a loop. 通过循环连续进行。 The client send a message first. 客户端首先发送一条消息。 Without the loop the program work but with the loop, it doesn't. 没有循环,程序就可以工作,但是有了循环,它就不能。 Below are the programs: 以下是程序:

public static void main(String[] args)  {
    // SERVER

    try
    {
        ServerSocket s = new ServerSocket(11);
        Socket s1 = null;
        int i=0;
        while (true)
        {
            s1 = s.accept();
            BufferedReader b = new BufferedReader(new InputStreamReader(s1.getInputStream()));
            PrintWriter p = new PrintWriter(new OutputStreamWriter(s1.getOutputStream()));
            String m;
            while ((m=b.readLine())!=null)
            {
                i++;
                System.out.print(m);
                p.print("reply"+i);
            }
        }

    }catch(IOException e){}

}

public static void main(String[] args) throws IOException {
    // CLIENT

    Socket s = new Socket("192.168.100.3",11);
    int i = 0;

    PrintWriter p = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

    p.print("msg"+i);
    BufferedReader b = new BufferedReader(new InputStreamReader(s.getInputStream()));

    while (true){
        PrintWriter p1 = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

        BufferedReader b1 = new BufferedReader(new InputStreamReader(s.getInputStream()));

        String m;
        while((m=b1.readLine())!=null)
        {               
            System.out.print(m);
            p1.print("msg"+i);
        }
        i++;
        p1.flush();
    }
}

When you use readLine() it reads up to the end of line. 当您使用readLine()它会读取到行尾。

However, print(x) doesn't write a newline. 但是, print(x)不会写换行符。

If you write and flush a println(x) there is be a new line at the end of your text to read. 如果您编写并刷新println(x) ,则在文本末尾会有新行要读取。

Does it make sense to loop and accept on the same socket? 在同一个套接字上循环并接受是否有意义? as in: 如:

Socket s1 = null;
while (true) {
  s1 = s.accept();

Also, I don't think it would work on port 11 as you have in your code there. 另外,我认为它不能像您在代码中那样在端口11上运行。 Try port numbers above 1024, those are not privileged. 尝试大于1024的端口号,这些端口没有特权。

This code will just deadlock. 此代码将陷入僵局。 Both ends are reading. 两端都在阅读。 Somebody needs to send something first, ensuring that it is line-terminated so that the peer's readLine() call will return. 有人需要先发送一些东西,确保它是行终止的,以便对等方的readLine()调用将返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM