java中的基于套结字(socket)的通信 一. 一个双人单方向通信例子

1/5/2008来源:Java教程人气:5365


  /*
* date: 2004-11-29 author:zhangyu6050;
* todo:一个双人单方向通信例子
* 本文件是主机方(Server)
* 提供主机与客户机的通信套节字:fromClient
* bugs:
*/

import java.net.*;
import java.io.*;

public class ChatServer {

public static void main(String[] args) {

final int port = 1775; //建立通信的主机的端口号
ServerSocket socServer = null;
Socket fromClient=null;//主机与客户机的通信套节字:fromClient
String message="hello,i'm server!";
try
{
socServer = new ServerSocket(port);
}
catch (IOException e)
{
System.err.PRintln("Could not listen on port: "+port);
System.exit(1);
}

Socket clientSocket = null;
try {
fromClient = socServer.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
try{
ObjectOutputStream oos=new ObjectOutputStream(fromClient.getOutputStream());

oos.writeObject(message);
oos.close();
fromClient.close();//关闭套节字前要关闭所有的流连接

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

}




/*
* date: 2004-11-29
* author:zhangyu6050;
* todo: 一个双人单方向通信例子
* 本文件是客户方(client)
* bugs:
*/
import java.net.*;
import java.io.*;
public class ChatClient {
public static void main(String[] args) {
final int port=1775;
Socket socket=null;
try {
socket=new Socket("127.0.0.1",port);
ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
String mess=(String)ois.readObject();
System.out.print(mess);



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