java中的基於套結字(socket)的通訊 一. 一個雙人單方向通訊例子
來源:互聯網
上載者:User
/*
* 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();
}
}
}