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();
}
}
}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.