简体   繁体   English

Java TCP客户端和服务器

[英]java tcp client and server

I have the following host 我有以下主持人

package clserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;


public class Main {
//instance vars
static ServerSocket sSocket = null;
static int serverPort = 0;
static Socket cSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;


public static void main(String[] args) throws IOException {
        System.out.println("\n\n\nTCP Server Client\n\nEnter port number:");
        Scanner scan = new Scanner(System.in);
        serverPort = scan.nextInt();
        try {
            //connect server to port
            sSocket = new ServerSocket(serverPort);
        } catch (IOException ex) {
            System.err.println("That port is busy");
        }
        try {
            //accept client connection
            cSocket = sSocket.accept();
        } catch (IOException ex) {
            System.err.println("Connection failed");
        }

        out = new PrintWriter(cSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));

        System.out.println(in.readLine());

      }
}

and this client code 和这个客户代码

package clclient;

import java.io.*;
import java.net.*;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Main {

    //instance vars
    static Socket cSocket =null;
static PrintWriter out = null;
static BufferedReader in = null;

//server info
static String serverName = null;
static int serverPort = 0;


public static void main(String[] args) {
    try {
        System.out.println("\n\n\nTCP Chat Client\nEnter server name:");
        Scanner scan = new Scanner(System.in);
        //get server info from user
        serverName = scan.nextLine();
        System.out.println("\nEnter port number:");
        serverPort = scan.nextInt();
        //make connection to server
        cSocket = new Socket(serverName, serverPort);
        out = new PrintWriter(cSocket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
    } catch (UnknownHostException ex) {
        System.err.println("\ncan't find that host\n");

    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

    String nm = "testing";
    out.print(nm);


}

} }

I am trying to send messages back and forth between them but when I send a message the host crashes. 我正在尝试在它们之间来回发送消息,但是当我发送消息时,主机崩溃了。 It throws the exception Java.net.SocketException:connection reset 抛出异常Java.net.SocketException:connection reset

Nope. 不。 print() just sends the data. print()仅发送数据。 println() sends the data and a line terminator. println()发送数据和一个行终止符。 readLine() blocks until a line terminator is received. readLine()阻塞,直到收到行终止符为止。 So somewhere along the line you have to call println(), or send a line terminator some other way. 因此,必须沿着行的某个地方调用println()或以其他方式发送行终止符。

I haven't used Java sockets for a while, but the following fixes it on my machine: 我已经有一段时间没有使用Java套接字了,但是以下内容可以在我的机器上修复它:

In the client, call out.println(nm) instead of out.print(nm) . 在客户端中,调用out.println(nm)而不是out.print(nm)

I think it may have something to do with automatic flushing, where println autoflushes but print does not. 我认为这可能与自动冲洗有关,其中println自动冲洗,而print没有。 Still, not sure off the top of my head why print would cause a Socket exception. 不过,仍然不确定为什么print会导致Socket异常。

Edit: you really should be doing everything with the Sockets within a try , and have a finally that calls close() on the Sockets. 编辑:您真的应该在try内使用Socket进行所有操作,并finally调用Socket上的close()

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

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