1.OutputStream,InputStream均为抽象类,不可实例化。需要使用ServerSocket来getOI.
2.定义客户端的Socket(),需要查看构造函数,而非服务器端使用ServerSocket.accept()
3.Socket会抛出UnknownHostException异常。所以也需要try()catch()
代码如下:
服务器端:
import java.net.;
import java.io.
;

public class TestServer1 {
public static void main(String[] args) {
OutputStream os = null;
InputStream is = null;
try {
ServerSocket ss = new ServerSocket(5889);
Socket s = ss.accept();
is = s.getInputStream();
os = s.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
String cc = null;
if((cc=dis.readUTF()) != null) {
System.out.println(cc);
}
dos.writeUTF(“Hey!”);
dos.close();
dis.close();
s.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
客户端:
import java.net.;
import java.io.
;

public class TestClient1 {
public static void main(String[] args) {
OutputStream os = null;
InputStream is = null;
try {
Socket s = new Socket(“127.0.0.1”,5889);
is = s.getInputStream();
os = s.getOutputStream();
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(“Hey!”);
String cc = null;
if((cc = dis.readUTF()) != null)
System.out.println(cc);
dis.close();
dos.close();
s.close();
} catch(UnknownHostException e) {
e.printStackTrace();
}

	catch(IOException e) { 		e.printStackTrace(); 	} } 

}

  • 版权声明:文章来源于网络采集,版权归原创者所有,均已注明来源,如未注明可能来源未知,如有侵权请联系管理员删除。

发表回复

后才能评论