In Java, a communication based on a socket (socket). A two-person single direction communication example

Source: Internet
Author: User
Tags date exit final net socket client port number
/*
* Date:2004-11-29 author:zhangyu6050;
* TODO: a two-person single direction communication example
* This file is the host side (Server)
* Provide communication between host and client sockets: Fromclient
* Bugs:
*/

Import java.net.*;
Import java.io.*;

public class Chatserver {

public static void Main (string[] args) {

Final int port = 1775; The port number of the host that established the communication
ServerSocket socserver = null;
Socket fromclient=null;//host and client communication sockets Word: 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 ();//close all stream connections before closing a set of words

catch (IOException E1) {
E1.printstacktrace ();
}
}

}




/*
* date:2004-11-29
* AUTHOR:ZHANGYU6050;
* TODO: a two-person single direction communication example
* This document is Customer side (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 ();
}
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.