------解决方法--------------------------------------------------------的程序如下:
客户端:
import java.io.*;
import java.net.*;
public class Client
{
PrintStream streamToServer;
BufferedReader streamFromServer;
Socket toServer;
public Client()
{
connectToServer();
}
private void connectToServer()
{
try
{
String name;
toServer = new Socket( "localHost ",1001);
streamFromServer = new BufferedReader(new InputStreamReader
((toServer.getInputStream())));
streamToServer = new PrintStream(toServer.getOutputStream());
System.out.print( "Enter connection name: ");
BufferedReader reader = new BufferedReader(new InputStreamReader
(System.in));
name = reader.readLine();
streamToServer.println(name);
String str = streamFromServer.readLine();
System.out.println( "The Server says: "+str);
}
catch(Exception e)
{
System.out.println( "Exception "+e);
}
}
public static void main(String[] args)
{
new Client();
}
}
服务器端:
import java.io.*;
import java.net.*;
public class Server implements Runnable
{
ServerSocket serverSocket;
PrintStream streamToClient;
BufferedReader streamFromClient;
Socket fromClient;
static int count = 0;
Thread thread;
public void Server()
{
try
{
serverSocket = new ServerSocket(1001);
}
catch (Exception e)
{
System.out.println( "Socket could not be created "+e);
}
thread = new Thread(this);
thread.start();
}
public void run()
{
try
{
while(true)
{
fromClient = serverSocket.accept();
count++;
System.out.println( "Client connection no: "+count);
streamFromClient = new BufferedReader(new InputStreamReader
((fromClient.getInputStream())));
streamToClient = new PrintStream(fromClient.getOutputStream());
String str = streamFromClient.readLine();
System.out.println( "Client connection name: "+str);
streamToClient.println( "Welcome "+str);
}
}