我将原来的代码做了修改(将整块程序改成了一个个函数),编译通过了,但是执行时出现如下提示:
java.net.ConnectException: Connection refused: connect
我对J2SDK可以说是门外汉(实在太菜了!)。请帮我看看问题出在什么地方!
原来的代码:
// tcpClient.java by fpont 3/2000// usage : java tcpClient <server> <port>
// default port is 1500import java.net.*;
import java.io.*;public class tcpclient 
{   
    
    public static void main(String[] args) 
{
///// init
int port = 1500;
Socket socket = null;
String lineToBeSent;
BufferedReader input;
PrintWriter output;
int ERROR = 1;

// connect to server
try 
{
    !
socket = new Socket("localhost",port);       System.out.println("Connected with server " +socket.getInetAddress() +":" + socket.getPort());
}
catch (UnknownHostException e) 
{
    System.out.println(e);
    System.exit(ERROR);
}
catch (IOException e) {
    System.out.println(e);
    System.exit(ERROR);
} try 
{
    input = new BufferedReader(new InputStreamReader(System.in)); 
    output = new PrintWriter(socket.getOutputStream(),true);
    
    // get user input and transmit it to server
    while(true) 
{
lineToBeSent = input.readLine();
// stop if input line is "."
if(lineToBeSent.equals(".")) break;
output.println(lineToBeSent);
    }
}
catch (IOException e) {
    System.out.println(e);
} try 
{
    socket.close();
}
catch (IOException e) 
{
    System.out.println(e);
}
    }    
}修改后的代码:
import java.net.*;
import java.io.*;public class mzh_client
{
public static void main(String args[])
{
int port = 1500;
Socket socket = null;
String lineToBeSent;
BufferedReader input;
PrintWriter output;
//biuld connection
mzh_connect(socket,port); //get user message
try
{
input= new BufferedReader(new InputStreamReader(System.in));
output = new PrintWriter(socket.getOutputStream(),true);
lineToBeSent = input.readLine();
mzh_getandsent(output,lineToBeSent); }
catch (IOException e) 
{
    System.out.println(e);
}
} public static void mzh_connect(Socket socket,int port)
{
try 
{
socket = new Socket("localhost",port);           System.out.println("Connected with server " +socket.getInetAddress() +":"                         + socket.getPort());
}
catch (UnknownHostException e)
{
    System.out.println(e);
    System.exit(1);
}
catch (IOException e) 
{
    System.out.println(e);
    System.exit(1);
}
} public static void mzh_close(Socket socket)
{
try 
{
    socket.close();
}
catch (IOException ioe) 
{
    System.out.println(ioe);
}
}
public static void mzh_getandsent(PrintWriter output,String message)
{
    while(true) 
    {
if(message.equals(".")) 
{
break;
}
output.println(message);
    }

////这里本来有个“CATCH”,但是因为编译时提示出错,所以删掉了!

}
}