Java TCP通信(服務器和客戶端代碼)

功能:實現客戶端和服務器端的聊天功能,目前只能從客戶端向服務器端單向發消息,對消息條數無限制

1、客戶端

import java.io.*;
import java.net.*;
import java.util.Scanner;

class  TcpClient
{
	public static void main(String[] args) throws Exception 
	{
		Scanner sc = new Scanner(System.in);
		String str = new String("start");
		String endStr = new String("game over");

		//創建客戶端的socket服務。指定目的主機和端口
		Socket s = new Socket("10.11.2.251",10003);
		
		//爲了發送數據,應該獲取socket流中的輸出流。
		OutputStream out = s.getOutputStream();

		while (!(str.equals(endStr)))
		{
			str = sc.nextLine();
			out.write(str.getBytes());
		}

		s.close();
	}
}

2、服務器端

class TcpServer {
	public static void main(String[] args) throws Exception
	{
		
		String endStr = new String("bye bye");

		//建立服務端socket服務。並監聽一個端口。
		ServerSocket ss = new ServerSocket(10003);

		Socket s = ss.accept();

		String ip = s.getInetAddress().getHostAddress();
		System.out.println(ip+".....connected");

		//獲取客戶端發送過來的數據,那麼要使用客戶端對象的讀取流來讀取數據。
		InputStream in = s.getInputStream();
		
		
		byte[] buf = new byte[50];
		in.read(buf);
		String msgStr = new String(buf,"utf-8");
		msgStr = msgStr.trim();	//去除字符串前後的空格
				
		
		while (!(msgStr.equals(endStr)))
		{
			System.out.println(msgStr);
			
			buf = new byte[buf.length];
			in.read(buf);
			msgStr = new String(buf,"utf-8");
			msgStr = msgStr.trim();
			
		}		
		
		System.out.println("bye bye\n聊天結束!");
		ss.close();
		s.close();//關閉客戶端.
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章