服务端01;
import java.io.*;
import java.net.*;
public class TestServer01 {
public static void main(String args[]){
try {
ServerSocket s = new ServerSocket(8888);
while (true){
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("Hello"+s1.getInetAddress()+"port#"+s1.getPort()+"bye_bye");
dos.close();
s1.close();
}
}catch (IOException e){
e.printStackTrace();
System.out.println("程序运行出错:"+e);
}
}
}
客户端02;
import java.io.*;
import java.net.*;
public class TestClient01 {
public static void main(String args[]){
try{
Socket s1 = new Socket("127.0.0.1",8888);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s1.close();
}catch (ConnectException connExc){
connExc.printStackTrace();
System.out.println("服务器连接失败");
}catch (IOException e){
e.printStackTrace();
}
}
}
客户端运行结果;
Hello/127.0.0.1port#64356bye_bye
服务端02;
import java.io.*;
import java.net.*;
public class TestServer02 {
public static void main(String args[]){
InputStream in = null;
OutputStream out = null;
try{
ServerSocket ss = new ServerSocket(8887);
Socket socket = ss.accept();
in = socket.getInputStream();
out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
DataInputStream dis = new DataInputStream(in);
String s = null;
if ((s=dis.readUTF())!=null){
System.out.println(s);
System.out.println("from:"+socket.getInetAddress());
System.out.println("port:"+socket.getPort());
}
dos.writeUTF("hi hello");
dis.close();
dos.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
客户端02;
import java.io.*;
import java.net.*;
public class TestClient02 {
public static void main(String args[]){
InputStream in = null;
OutputStream out = null;
try {
Socket socket = new Socket("127.0.0.1",8887);
in = socket.getInputStream();
out = socket.getOutputStream();
DataInputStream dis = new DataInputStream(in);
DataOutputStream dos = new DataOutputStream(out);
dos.writeUTF("hey");
String s = null;
if ((s=dis.readUTF())!=null);
System.out.println(s);
dos.close();
dis.close();
socket.close();
}catch (UnknownHostException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
服务端运行结果;
hey
from:/127.0.0.1
port:64591