我正在使用Socket和ServerSocket类在本地主机上进行通信 客户发送否。到服务器和服务器计算no的平方。并发送回客户端
// Client Class
import java.net.*;
import java.io.*;
class SocketDemo
{
public static void main(String...arga) throws Exception
{
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
System.out.println("Enter a number one digit");
int i=(System.in.read()-48); // will read only one character
System.out.println("Input number is "+i);
try
{
s = new Socket("127.0.0.1",10101);
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println("Connection established, streams created");
}
catch(Exception e)
{
System.out.println("Exception in Client "+e);
}
pw.println(i);
System.out.println("Data sent to server");
String str = br.readLine();
System.out.println("The square of "+i+" is "+str);
}
}
// Server Side
import java.io.*;
import java.net.*;
class ServerSocketDemo
{
public static void main(String...args)
{
ServerSocket ss=null;
PrintWriter pw = null;
BufferedReader br = null;
int i=0;
try
{
ss = new ServerSocket(10101);
}
catch(Exception e)
{
System.out.println("Exception in Server while creating connection"+e);
}
System.out.print("Server is ready");
while (true)
{
System.out.println (" Waiting for connection....");
Socket s=null;
try
{
s = ss.accept();
System.out.println("Connection established with client");
pw = new PrintWriter(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
i = new Integer(br.readLine());
System.out.println("i is "+i);
}
catch(Exception e)
{
System.out.println("Exception in Server "+e);
}
System.out.println("Connection established with "+s);
i*=i;
pw.println(i);
try
{
pw.close();
br.close();
}
catch(Exception e)
{
System.out.println("Exception while closing streams");
}
}
}
}
请帮助
答案 0 :(得分:1)
在客户端,在将数据发送到服务器
后执行此操作 pw.println(i);
pw.flush();