服务器端:
package p1;
import java.net.*;
import java.io.*;
public class s1 {
public static void main(String[] args)
{
int port =8888;
BufferedReader br;
PrintWriter pw;
ServerSocket ss;
Socket s;
try
{
ss = new ServerSocket(port);
s=ss.accept();
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
System.out.println("wait.....");
while(true)
{
String str=br.readLine();
System.out.println(str);
pw.println("服务器返回:"+str);
}
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
发送端:
package p1;
import java.net.*;
import java.io.*;
import com.sun.org.apache.bcel.internal.generic.NEW;
public class c1 {
public static void main(String[] args)
{
try {
InetAddress add=InetAddress.getByName("localhost");
Socket s=new Socket(add,8888);
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String message=reader.readLine();
pw.println(message);
pw.flush();
//String str;
String str=br.readLine();
System.out.println(str);
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}